diegohaz/constate

Can the container be used outside react components as a global store ?

lishine opened this issue · 7 comments

Can the container be used outside react components as a global store ?

Could you elaborate more?

container.setState({count: 1})
Not in react component

Like easy-peasy for example

Got it. No, it doesn't work.
If people come up with use cases and API/implementation ideas, we can think about something like this.

In Next.js
I want to make the pathname be available to all components.
I assign the pathname to global store in getInitialProps.
But getInitialProps is get called before render.
Same for authentication status

Does something like this work?

// normal context
PathContext = React.createContext(null);

// in getInitialProps
return { path };

// in app render
<PathContext.Provider value={this.props.path}>
  ...
</PathContext.Provider>

// in another child component
const path = React.useContext(PathContext);
console.log(path);

Yes, thanks for the illustration.
This pathname is assigned in the _app getInitialProps. But it is not available in other components' getInitialProps. Of course in this case, the other components' getInitialProps receives pathname anyway, but for authentication status I can add it to it's props. So it is solvalbe of course.
But suppose I have some other store which is not in a component but outside - it cannot access the context, so it cannot get these variables.