Nextjs redux, thunk and getInitialProps - how to implement
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
.
marczak
Updated on April 16, 2020Comments
-
marczak about 4 years
I want to use
nextjs
in my new project withredux
andthunk
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?
- Implemented store (base on next-redux-wrapper in _app.js)
- Created
HOC
component (like below) withmapStateToProps
andmapDispatchToProps
Currently I thinking about use somehow
this.props.fetchUsers
method intogetInitialProps
- documentation say that this method should be used to fetch data before render site.Please help me with correctly
redux
implementation fornextjs
-
marczak almost 6 yearsSo
mapDispatchToProps
is unnecessary innextjs
for that? -
marczak almost 6 yearshow do that after refresh page? I mean on server side? On Client side it's working (used Link) but on server not.
-
giggi__ almost 6 years
mapDispatchToProps
is unnecessary in pages if you dispatch actions only ingetInitialProps
. Furthermore, it should work even if you reload the page. If you are using redux devtools, you will not see dispatched action because on reload it is made server side. -
marczak almost 6 yearsBut on server side it doesn't work. As I investigated store.dispatch not work on server side. I tried console log in reducer but on server console it doesn't present.
-
Ewomazino Ukah about 5 yearsplease does this mean that there is not need to implement 'componentDidMount' for fetching the data on the client side for client side routing ?
-
giggi__ about 5 years@MazinoSUkah it depends on your needs. If you have to dispatch actions in routes you can avoid
componentDidMount
-
julesbou over 4 years@marczak you need to use with
await
, like this:await store.dispatch(...)
-
IgalSt about 4 yearsTake a look at
connect-initial-props
, this is a small decorator I've created to get state and dispatch easily fromgetInitialProps
github.com/webiya/connect-initial-props