Skip to content

conditionUpdating

Method to set conditions for when state updates should occur.

Description

The conditionUpdating method allows you to define a condition that must be met before the state is actually updated. The callback function receives both the previous and new values and returns a boolean indicating whether the update should proceed.

Input/Output

InputTypeDescription
callback(previousValue: T, newValue: T) => booleanFunction that determines if update should occur
OutputTypeDescription
ReturnsvoidNo return value

Example

typescript
import { signify } from 'react-signify';
import React from 'react';

const sScore = signify(0);
const sUsername = signify('');

// Only allow score updates if new value is higher
sScore.conditionUpdating((prev, next) => {
  return next > prev; // Only update if score increases
});

// Only allow non-empty usernames
sUsername.conditionUpdating((prev, next) => {
  return next.trim().length > 0; // Only update if not empty
});

function GameComponent() {
  const currentScore = sScore.use();
  const name = sUsername.use();
  
  const tryUpdateScore = (newScore: number) => {
    sScore.set(newScore); // Will only update if newScore > currentScore
  };
  
  const tryUpdateUsername = (newName: string) => {
    sUsername.set(newName); // Will only update if name is not empty
  };
  
  return (
    <div>
      <h2>Player: {name || 'Anonymous'}</h2>
      <p>Score: {currentScore}</p>
      
      <button onClick={() => tryUpdateScore(currentScore + 10)}>
        Add 10 Points (✓ Will work)
      </button>
      <button onClick={() => tryUpdateScore(currentScore - 5)}>
        Subtract 5 Points (✗ Won't work)
      </button>
      
      <input 
        placeholder="Enter username"
        onBlur={(e) => tryUpdateUsername(e.target.value)}
      />
    </div>
  );
}

Released under the MIT License.