I've been struggling to integrate Redux into a Next.js app, particularly when trying to use the dispatch function within getInitialProps
. For some reason, the store keeps returning as undefined and I can't seem to pinpoint the issue. I've followed the instructions on the next-redux-wrapper GitHub page, but something seems to be going wrong along the way. I know the code is functional - when I used axios to directly fetch the artPieces
, it worked perfectly. However, my goal is to utilize Redux instead. The transition I'm making involves transforming a React/Express.js app into a Next.js app where I plan to rely on an API for essential server operations needed for a small blog application.
Here's a snippet from my store.js
:
import { createStore } from 'redux';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';
// reducer implementation
const reducer = (state = { tick: 'init' }, action) => {
switch (action.type) {
case HYDRATE:
return { ...state, ...action.payload };
case 'TICK':
return { ...state, tick: action.payload };
default:
return state;
}
};
// makeStore function definition
const makeStore = (context) => createStore(reducer);
// exporting an assembled wrapper
export const wrapper = createWrapper(makeStore, { debug: true });
Next, let's look at the _app.js
:
import './styles/globals.css';
import { wrapper } from '../store';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default wrapper.withRedux(MyApp);
Lastly, this is where the problem arises - attempting to call the dispatch function on the context within a sub component of _app.js
:
import React from 'react';
import { ArtPiecesContainer } from './../components/ArtPiecesContainer';
import { useDispatch } from 'react-redux';
import axios from 'axios';
import { getArtPieces } from '../reducers';
const Art = ({ data, error }) => {
return (
<>
<ArtPiecesContainer artPieces={data} />
</>
);
};
export default Art;
Art.getInitialProps = async ({ ctx }) => {
await ctx.dispatch(getArtPieces());
console.log('DATA FROM GETARTPIECES', data);
return { data: ctx.getState() };
};