How to use redux-thunk with Next.js?

The problem

static getInitialProps ({ store, isServer }) {
store.dispatch(serverRenderClock(isServer))
store.dispatch(addCount())
return { isServer }
}

The solution

// Items model (models/items.js)
// -----------------------------
import axios from 'axios';export default function reducer (state = [], action) {
switch (action.type) {
case 'SET_ITEMS':
return action.items;
default:
return state;
}
}
export function fetchItems () {
return dispatch => axios.get('/api/items')
.then(({ data }) => data)
.then(items => dispatch({ type: 'SET_ITEMS', items }));
}

// Items page (pages/items.js)
// ---------------------------
import React from 'react';
import withRedux from 'next-redux-wrapper';
import { fetchItems } from '../models/items';
import { initStore } from '../store';
const Page = () => (
<div>
Rendering subcomponents...
</div>
);
// Option 1 - Returning the Promise
Page.getInitialProps = ({ store }) => store.dispatch(fetchItems());
// Option 2 - Using async / await
Page.getInitialProps = async ({ store }) => {
await store.dispatch(fetchItems());
};
export default withRedux(initStore)(Page);

--

--

--

I think one of the most important thing in our life is curiosity. Stay curious, understand truly how things work and become a master craftsman. This is my goal.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Levente Balogh

Levente Balogh

I think one of the most important thing in our life is curiosity. Stay curious, understand truly how things work and become a master craftsman. This is my goal.

More from Medium

Customizing a Drawer Element in a Quick App

Comparing Astro and Next for React apps

Add hCATPCHA to your Next.js App

Implementing blocking announcements in smallcase frontend