GitHub package.json versionTypeScriptNPM
GitHub package.json versionTypeScriptNPM

store.setState Usage

Signature:

(changes: Changes<State>) => void;

About the store setState method

[This store's] internal state is immutable and private.
Direct mutation attempts on its properties have no effect.

New updates are merged into state by default.

So only supply the exact changes to be merged (i.e. do not spread the new state changes into the current state as is commonly done in React development).

And to overwrite a slice of state, use the tag command.

Do this:
setState({ stateKey0: changes0 });
Not this:
setState({
    ...state,
    stateKey0: {
        ...state.stateKey0,
        ...changes0
    }
});

Batched Update

provides a way to update the state as a transaction of several state changes.

This can be achieved by collecting a series of state changes in an array and passing that array as an argument to the store.setState method.

The state changes are resolved sequentially from index 0 to the last index.

Clients are only notified at batched update completion.

Do this:
setState([
    { stateKey0: changes0 },
    { stateKey1: changes1 },
    // et cetera ... et cetera
]);
Not this:
setState([
    { ...state, stateKey0: { ...state.stateKey0, ...changes0 } },
    { ...state, stateKey1: { ...state.stateKey1, ...changes1 } },
    // et cetera ... et cetera
]);

Indexing

Traditionally, array state properties are updated by a new array replacement. This overwrites the existing state property.

Hence the need for indexing. Indexing provides a mechanism for updating array state properties at specific indexes using an indexed state change object.

Note: The store also recognizes and resolves negative indexes when present in the indexed state change object. See additional tip below.

Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Given the following array bearing state object: const state = { a: { b: [ { x: 7, y: 8, z: 9 } ] }, j: 10 }; // The following will override the existing array. store.setState({ a: { b: [ { y: 30 }, 22 ] } }); // updates the state to: { a: { b: [ { y: 30 }, 22 ] }, j: 10 }; // The followinng will update the existing array at indexes. store.setState({ a: { b: { 0: { y: 30 }, 1: 22 } } }); // updates the state to: { a: { b: [ { x: 7, y: 30, z: 9 }, 22 ] }, j: 10 }; // The followinng will update the existing array at indexes. store.setState({ a: { b: { '-1': { y: 30 }, 1: 22 } } }); // updates the state to: { a: { b: [ { x: 7, y: 30, z: 9 }, 22 ] }, j: 10 }; // The previous 2 statements are functionally equivalent to the following: const [ first, second, ...rest ] = state.a.b; store.setState({ ...state, a: { ...state.a, b: [ { ...first, y: 30 }, 22, ...rest ] } }); // Refrain from doing this, please!
Tip:
Negative indexing pointing at an out-of-bounds index is ignored.

Overwriting state using the tag commands

Please see full info on tag commands here.