Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nextjs redux, thunk and getInitialProps - how to implement

I want to use nextjs in my new project with redux and thunk also. I wondering how to implement all packages correctly.

In my previous projects pages has HOC components like:

import {connect} from 'react-redux';
import Page from './about';
import {fetchUsers} from '../../actions/user';

const mapStateToProps = (state) => {
    const {users} = state;
    return users;
};

const mapDispatchToProps = (dispatch) => {
    return {
        fetchUsers: () => dispatch(fetchUsers())
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Page);

And method to fetch users I implemented in componentDidMount

How to implement the same logic for nexjs?

What have I do?

  1. Implemented store (base on next-redux-wrapper in _app.js)
  2. Created HOC component (like below) with mapStateToProps and mapDispatchToProps

Currently I thinking about use somehow this.props.fetchUsers method into getInitialProps - documentation say that this method should be used to fetch data before render site.

Please help me with correctly redux implementation for nextjs

like image 768
marczak Avatar asked Jul 25 '18 07:07

marczak


People also ask

What is getInitialProps Nextjs?

getInitialProps enables server-side rendering in a page and allows you to do initial data population, it means sending the page with the data already populated from the server. This is especially useful for SEO. getInitialProps will disable Automatic Static Optimization.


1 Answers

You can follow this example The correct way is to pass the store to the getInitialProps context and to the App component so you can pass it to the Provider.

The getInitialProps can't access to instance of the component, this is not accessible, so you can't call this.props.fetchUsers, but, because you are passing store to its context, you can do store.dispatch(fetchUsers()) and remove dispatch from mapDispatchToProps.

Generally I dispatch actions in getInitialProps and then map state to props within connect.

like image 147
giggi__ Avatar answered Sep 20 '22 01:09

giggi__