React Context always returns EMPTY

1.1k views Asked by At

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

3

There are 3 answers

3
Spyna On BEST ANSWER

I wrote that article.

To solve your specific problem:

When using the HOC withStore you're injecting the prop store into the wrapped component: <WrappedComponent store={context}. The value of the prop store is an object that contains 3 functions: get, set, and remove.

So, instead of printing it, you should use it. For example this.props.store.get("currentAlbums") or this.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.

7
Gabriele Petrioli On

You pass the store as a prop, so to access it, you need this.props.store in your SideBar.

Not this.state.store

0
Petar Petrovic On

Create a wrapping App component around Search and Sidebar:

const App = props => (
  <div>
    <Search />
    <SideBar />
  </div>
);
export default createStore(App);

Now you can manipulate state with set and get that you have available in child components Search and Sidebar.

In Search component you can have something like:

  componentDidMount() {
    this.props.store.set("showModal", this.state.showModal);
  }

also wrapped with withStore(Search) ofc.

and in SideBar you can now call:

  render() {
    return (
      <div>
        {"Sidebar: this.state.store: ---> " +
          JSON.stringify(this.props.store.get("showModal"))}
        }
      </div>
    );
  }

and you will get the output.