Cannot get redux state inside the provider file

Viewed 44

I'm trying to get the redux state value in the same file as where I use the provider.

For some reason it seems it cannot find the value.

const MyApp = ({ Component, pageProps }: AppProps)=> {

  const isDark = useSelector<ThemeState, ThemeState["isDark"]>(state => state.isDark)
  const dispatch = useDispatch()

  return (
    <>
    <Provider store={ThemeStore}>
      <div className={isDark ? 'dark' : 'white'}>
      <Player />
      <Component {...pageProps} />
      </div>
      </Provider>
    </>
  )
}
export default MyApp

This gives an error:

Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

When using the same useSelector and dispatch inside my nav component, it does work.

Any idea how I could make it work inside the _app.js file?

1 Answers

You can not use state in the provider like that, you need to go at least one layer deeper or just use what you're passing to the state directly not from calling to useSelector, try this:

function Child({ children }) {
  const isDark = useSelector<ThemeState, ThemeState["isDark"]>(state => state.isDark)

  return <div className={isDark ? "dark" : "white"}>{children}</div>;
}

const MyApp = ({ Component, pageProps }: AppProps) => {
  return (
    <Provider store={ThemeStore}>
      <Child>
        <Player />
        <Component {...pageProps} />
      </Child>
    </Provider>
  );
};
export default MyApp;
Related