diegohaz / constate

React Context + State

Home Page:https://codesandbox.io/s/github/diegohaz/constate/tree/master/examples/counter

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

If reading global state, is nesting containers needed to modify local state?

ripern opened this issue · comments

In my component I need to read global state (context="app") but I also need to update local state, what is the best practice for combining that using constate? Below is an example that isn't working but just to get you some kind of idea what I've tried. Is nesting containers needed here?
(I got another related question about onUnmount also but I think it's better to add that later to not make this more complex than necessary.)

updateFoobar is triggered in MyView and should update local state.

const initialState = {
  foobar: false,
}

const effects = {
  ...
}

const effectsLocal = {
  updateFoobar: value => ({ setState }) => {
    setState({foobar: value})
  },
}

const MyView = props => (
  <Container
    initialState={initialState}
    effects={effectsLocal}>
    {(foobar, updateFoobar) => (
      <Container context="app" effects={effects}>
        {({ globalVar, setState }) => {
          return (
            <MyView
              {...props}
              globalVar={globalVar}
              updateFoobar={(value) => updateFoobar(value)}
            />
          )
        }}
      </Container>
    )}
  </Container>
)
commented

That's how I would do @ripern. You can also use something to compose containers, like react-adopt.