Could not find react-redux context value; please ensure the component is wrapped in a <Provider> in Reactjs

Dung Do Tien Oct 28 2021 144

I have created a small app with ReactJs, You can see App function very simple as below:

import { StrictMode, useEffect } from 'react'
import { Provider } from 'react-redux';
import { useDispatch } from 'react-redux';
import store from 'store';
import routes from 'routes/routes';
import PrivateRoute from 'routes/PrivateRoutes';

const App = () => {
  return (
    <StrictMode>
      <Provider store={store}>
         <Router>
            <Switch>
               Define some router here!!!
            </Switch>
          </Router>
      </Provider>
    </StrictMode>
  );
}

export default App;

But when running this method I got an error could not find react-redux context value; please ensure the component is wrapped in a <Provider>.

Bellow is my package.json 

"react": "16.9.0",
"react-native": "0.61.5",
"react-redux": "^7.1.3",
"redux": "^4.0.5",

I imported react-redux in my code but it still does not work for me.

How can I resolve it?

Have 2 answer(s) found.
  • V

    Vukosi Ndlamini Oct 29 2021

    You can create a wrapper component for <App> component:

    const AppWrapper = () => {
      const store = createStore(rootReducer);
    
      return (
        <Provider store={store}> // Set context
          <App /> // Now App has access to context
        </Provider>
      )
    }
    
    const App = () => {
      const dispatch = useDispatch(); // Works!
       ...
       
    }

    It worked for me!!

  • T

    Thắng Ngô Minh Oct 28 2021

    You can create a ParentApp, it will content  <Provider> and <App> 

    For an example:

    const AppWrapper = () => {
      const store = createStore(rootReducer);
    
      return (
        <Provider store={store}> // Set context
          <App />
        </Provider>
      )
    }
    
    
    const App = () => {
      return (
        <StrictMode>
          <Provider store={store}>
             <Router>
                <Switch>
                   Define some router here!!!
                </Switch>
              </Router>
          </Provider>
        </StrictMode>
      );
    }

    And it's worked for me. I hope it solve for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close