1.0.2 • Published 4 years ago

@kyle-villeneuve/deepstate v1.0.2

Weekly downloads
2
License
ISC
Repository
-
Last release
4 years ago

DeepState

Motivation

To make updating immutable objects and arrays more succinct and readable.

Usage

deepState(initialState, path, update);

initialState: an object or array you wish to update. This original value will never be mutated, a new copy will be created where item(s) at the end of the path are updated as specified by the update value or function.

path: an array of strings (keys) and/or objects (conditions). Objects can be used when the value at that particular path depth is an array. Objects keys are conditions that must be met for an element to be updated. For example, passing an object like the following would update all values in an array where name === 'example'

{
  name: 'example';
}

Object values can either be primitives or a function. As shown above, primitive values are the same as comparing strict equality, multiple object properties means that multiple conditions must be true for the element in the array to be updated.

When an object value is a function, if the function returns true then the element will be updated. The following example would update all elements in an array where the id > 5 && name === 'bob'

{ id: (id) => id > 5, name: 'bob' }

update: can either be a static value or a callback function where the element(s) at the end of the path are passed as an argument. The callback function must be pure and should never mutate the state directly. Alternatively, you can also pass any value you want to replace at the end of the path specified. All three examples below create a new state object with the same data.

// using a callback
// this is convenient when you want to perform more complex mutations
deepState(state, ['users', { id: 5 }, 'posts', { id: 2 }], post => ({
  ...post,
  title: 'updated post title',
}));
// using a value
deepState(
  state,
  ['users', { id: 5 }, 'posts', { id: 2 }, 'title'],
  'updated post title'
);
// handwritten
{
    ...state,
    users: state.users.map(user => user.id === 5 ?
        {
            ...user,
            posts: user.posts.map(post => post.id === 2 ? {
                ...post,
                title: "updated post title"
            }: post)
        } : user
    )
}
1.0.2

4 years ago

1.0.0

4 years ago