I'm building a web app using next.js & redux, and trying to fetch data from getInitialProps on server side.
There is a redux action ready to be triggered in getInitialProps and it gets triggered when I hit or refresh the page.
The problem is that after it gets triggered data get fetched from DB and stored in redux store successfully but the stored data never move to the page props so I cannot use the fetched data at all.
If I check "store.getState()" after the action triggered, there are data fetched from DB.
Funny thing is, if I click a button that triggers the same action, data get fetched and move to the page props so I can use them.
What do I do wrong here and how can I send the stored data to the page props automatically in the first place?
import Head from 'next/head'
import Link from 'next/link'
import { connect } from 'react-redux'
import { getItems } from '../../store/actions/itemAction'
const Index = props => {
return (
<>
<Head>
<title>Item List</title>
</Head>
<div>
<Button onClick={() => props.getItems()}>Get Items!</Button>
</div>
</>
)
}
Index.getInitialProps = async ({ store }) => {
await store.dispatch(getItems())
return {}
}
const mapStateToProps = state => ({
goods: state.item.goods,
})
const mapDispatchToProps = dispatch => ({
getItems: () => dispatch(getItems())
})
export default connect(mapStateToProps, mapDispatchToProps)(Index)
Here is the itemReducer.js
import { GET_ITEMS } from '../types'
const initialState = { goods: [], loading: false }
const itemReducer = (state = initialState, action) => {
switch (action.type) {
case GET_ITEMS:
return {
...state,
goods: action.payload,
loading: false,
}
default:
return state
}
}
export default itemReducer
getInitialProps
returns an empty object, removing whatever you had. However, when you update the state through the button, you get the values through the connect withoutgetInitialProps
does overridiring them. – Jose FelixIndex.getInitialProps
, and the fetched data are stored in global state, and the state is mapped to the page props throughmapStateToProps
, it turns out thatprops.item.goods
in the page is empty. I can know the fetched data are stored right after the dispatched action because when I console.logstore.getState()
after the dispatched action in thegetInitialProps
, it shows that there are data stored in the `goods' array. – Justin M