aweary / react-copy-write

✍️ Immutable state with a mutable API
MIT License
1.79k stars 54 forks source link

Replacing `this.setState()`? #41

Closed davej closed 6 years ago

davej commented 6 years ago

Is it possible to use react-copy-write to read/write local component state rather than from the Provider context?

A possible API might look like this?

import { createLocalState } = from "react-copy-write";

const { LocalState, localMutate } = createLocalState({
  user: {
    avatar: {
      src: 'my-avatar.png'
    }
  },
  theme: {
    avatar: {
      background: 'blue'
    }
  }
});

const Avatar = ({ size }) => (
  <LocalState consume={{size}} select={[
    state => state.user.avatar.src,
    state => state.theme.avatar,
  ]}>
    {(src, avatarTheme) => (
      <img
        onClick={() => localMutate(draft => {
          // Mutate state! You dont have to worry about it!
          draft.avatarClickCount++;
        })}
        className={`avatar-${size}`}
        src={src}
        style={avatarTheme} />
    )}
  </LocalState>
)
aweary commented 6 years ago

Hey @davej! Thanks for bringing this up. In general I don't think react-copy-write should replace regular React state. One of the best things about it is that you can use it alongside other stateful React components when necessary.

If you'd like to use the mutate method to update local state, try just importing immer directly. This is what RCW uses internally, and mutate is just a small wrapper around it.

Hope that helps!