I have a Search
parent component and a SideBar
child component, I am trying to get context in SideBar
, but everytime it returns empty.
I followed the tutorial exactly like: https://itnext.io/manage-react-state-without-redux-a1d03403d360 but it never worked, anyone know what I did wrong?
Here is the codesandbox link to the project: https://codesandbox.io/s/vigilant-elion-3li7v
I wrote that article.
To solve your specific problem:
When using the HOC
withStore
you're injecting the propstore
into the wrapped component:<WrappedComponent store={context}
. The value of the propstore
is an object that contains 3 functions:get
,set
, andremove
.So, instead of printing it, you should use it. For example
this.props.store.get("currentAlbums")
orthis.props.store.set("currentAlbums", [album1, album2])
.This example is forked by your code: https://codesandbox.io/s/nameless-wood-ycps6
However
Don't rewrite the article code, but use the library: https://www.npmjs.com/package/@spyna/react-store which is already packed, tested, and has more features.
An event better solution is to use this library: https://www.npmjs.com/package/react-context-hook. That is the new version of the one in that article.
This is an example of a sidebar that updates another component content: https://codesandbox.io/s/react-context-hook-sidebar-xxwkm
Be careful when using react context API
Using the React Context API to manage the global state of an application has some performance issues, because each time the context changes, every child component is updated. So, I don't recommend using it for large projects.
The library https://www.npmjs.com/package/@spyna/react-store has this issue.
The library https://www.npmjs.com/package/react-context-hook does not.