I'm building an isomorphic react app and the following tasks are performed when the user sends a request:
1) Suppose user hits /about-us
, react-routers matchPath
finds the appropriate component and returns it.
2) A static function named fetchData is called which dispatches an action aboutPageContent()
.
3) Once promise has been resolved on the server, getState gets called in order to get an updated state, but it returns the initialState of aboutPage and not the newly updated state.
Reducer gets a response but does not return a new state. (this happens only when action is dispatched by server).
getState on server returns:
{
aboutUs:{
founders:[{}]
story: ""
}
}
But it should return:
{
aboutUs:{
founders:[{name: 'abc'}]
story: "some random story"
}
}
server.js
app.get("*", (req, res) => {
const memoryHistory = createMemoryHistory(req.url)
const currentRoute = routes.find(r => matchPath(req.url, r))
const store = configureStore({}, memoryHistory)
if (currentRoute && currentRoute.component.fetchData) {
Promise.all(currentRoute.component.fetchData(store, req.url)).then(() => {
const content = (
<StaticRouter location={req.url} context={{}}>
<Provider store={store}>
<App />
</Provider>
</StaticRouter>
)
const htmlContent = renderToString(content)
const preloadedState = store.getState() <----- Returns initialState and not the updated state.
const html = renderToStaticMarkup(<HtmlDocument html={htmlContent} preloadedState={preloadedState} />)
res.status(200)
res.send(html)
})
}
})
aboutPageContainer.jsx
static fetchData = (store) => [store.dispatch(aboutPageContent())]
preloadedState gets assigned to window.__data
. And window.__data
gets called on client.js in order to load the client store.
Am I doing anything wrong? It's my first react-isomorphic app.
I think you need to subscribe to store here to get the update like below.
using store.subscribe
will make sure you get the updated state inside. Hope it helps. Read http://redux.js.org/docs/api/Store.html#subscribelistener
store.subscribe(() => {
// When state will be updated(in this case, when items will be fetched), this is how we can get updated state.
let items= store.getState().items;
})