Asking
Asking

Reputation: 4172

Using redux in NEXT.JS

In my application on Next.Js i use redux and redux saga. I want to use ssr making http requests:

export const getStaticProps = wrapper.getStaticProps(async ({ store }) => {
  store.dispatch(getDataRequest());
  store.dispatch(END);
  await store.sagaTask.toPromise();
});

In the same time i want to get data of the above result:

const selector = useSelector((s) => s);
  console.log(selector);

The issue is that, when i run the application i get an error:

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

I used the provider but the data doesn't appear.
Question: How to solve the issue in my application?
demo: https://codesandbox.io/s/awesome-butterfly-f7vgd?file=/pages/store/saga.js

Upvotes: 0

Views: 396

Answers (1)

Yilmaz
Yilmaz

Reputation: 49182

this is your _app component:

function App({ Component, pageProps }) {
  return (
    <div>
      <Provider store={makeStore}>
        <Component {...pageProps} />
      </Provider>
    </div>
  );
}

you dont need to wrap it with Provider. this is the only thing you need to do in _app.

export default wrapper.withRedux(App)

this is getStatisProps in your pages/index.js

export const getStaticProps = wrapper.getStaticProps(async ({ store }) => {
  store.dispatch(getDataRequest());
  store.dispatch(END);
  await store.sagaTask.toPromise();
});

see store is already passed here. You will be accesing state via store.getState(). this is how it should be

export const getStaticProps = wrapper.getStaticProps(async ({ store }) => {
      store.dispatch(getDataRequest());
      store.dispatch(END);
      await store.sagaTask.toPromise();
      const state = store.getState(); 
      return {props:{data:state}} // since you have only one reducer
    });

now data will be passed as a prop to your component. if you console.log(props.data) inside the component, you should be seeing your dataReducer

Upvotes: 1

Related Questions