Lukas Guldstøv
Lukas Guldstøv

Reputation: 101

Error with finding react-redux context value when wrapping App in provider?

I'm trying to wrap my outer App in nextjs in a Provider since I want to do a request on every refresh on every page to the backend, and it seems to be the easiest way I know. I looked here on stackoverflow where it was suggested to add a wrapper and pass the component to the app function. I get the following error though:

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

The code not working with dispatch in the App function:

import {useEffect} from 'React';
import {useDispatch} from 'react-redux'
import Router from 'next/router';
 
// redux
import { store } from '../store/store';
import { Provider } from 'react-redux'

import { UserInfoAsync } from '../store/reducers/user';
 


    export function AppWrapper({ Component, pageProps }) {
      return (
        <Provider store={store}>
          <Component {...pageProps} /> 
        </Provider>
      )
    }
    
    export default function App({ Component, pageProps }) {
      const dispatch = useDispatch()
      useEffect(() => {
        dispatch(UserInfoAsync());
      },[])
    
      return (
         <AppWrapper {...Component} {...pageProps} />
      )
    }

//<Provider store={store}>
//export default wrapper.withRedux(MyApp)

This is the question I tried: useDispatch() Error: Could not find react-redux context value; please ensure the component is wrapped in a <Provider>

Upvotes: 1

Views: 948

Answers (1)

juliomalves
juliomalves

Reputation: 50338

App itself is not wrapped by the Redux store provider so you can't call useDispatch from it.

A possible solution is to move the useDispatch call inside the AppWrapper, and wrap it with Provider in App.

export function AppWrapper({ Component, pageProps }) {
    const dispatch = useDispatch()

    useEffect(() => {
        dispatch(UserInfoAsync());
    }, [])

    return (
        <Component {...pageProps} /> 
    )
}
    
export default function App({ Component, pageProps }) {    
    return (
        <Provider store={store}>
            <AppWrapper Component={Component} pageProps={pageProps} />
        </Provider>
    )
}

Upvotes: 1

Related Questions