manuelbieh / react-ssr-setup

React Starter Project with Webpack 4, Babel 7, TypeScript, CSS Modules, Server Side Rendering, i18n and some more niceties

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ConnectedRouter always loading / on hydration due to unpopulated router state from server

limeandcoconut opened this issue · comments

commented

EDIT:
I was being foolish here and misrepresented the issue.
The problem is not that <StaticRouter> isn't rendering the correct route, it's that <ConnectedRouter> is switching to / no matter what is rendered by <StaticRouter>.

The issue seems to be that state.router.location isn't being initialized to the proper route.

I knew this was actually the problem but wrote the wrong thing initially because I'm a dummy.
☕️fixed me
/EDIT

When adding a <StaticRouter> to the app all pages are SSRed as /.

// in render.js

<Provider store={req.store}>
    <StaticRouter location={req.url} context={{}}>
        ...
    </StaticRouter>
</Provider>

const state = JSON.stringify(req.store.getState())
console.log('state', state)
// {"app":{"locale":"en_US"},
// "router":{"location":{"pathname":"/","search":"","hash":"","key":"hnge0b"},
// "action":"POP"}}

It looks to me like passing an inital state to createMemoryHistory would solve this problem. Something like:

return createMemoryHistory({
    initialEntries: [req.url],
})

This seems like a pretty large oversight, however, and I imagine there's a better way to do this or a fix I'm not aware of? Is this an error?

EDIT:
I also tried:

// sec/server/index.js
app.use((req, res, next) => {
    req.store = configureStore()
    req.store.dispatch(push('/page1')) //Add this line
    return next()
})

To no avail...
/EDIT

Same issue

commented

I've solved this. PR coming in soon.

How did you end up fixing this in the end? I'm having the same issue.

Curious to know, too. How did you do it @limeandcoconut 🙂