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?
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
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With