reactql / kit

ReactQL starter kit (use the CLI)
https://reactql.org
228 stars 38 forks source link

Initial State for server side rendering #117

Closed webexpert5 closed 6 years ago

webexpert5 commented 6 years ago

Hi, Could you please tell me how i can set the initial state on server.

This is my use case:

I have two separate home pages for authenticated and non authenticated user.

After logging in, I am storing the jwt with user details in localstorage as well as in cookie.

Now when I am on browser (port 8080), if i hit refresh everything works correctly, i.e the correct homepage is loaded. For this I am dispatching the set user action after creating the store in browser.js and getting the user value from local storage. So the state is set before anything is rendered.

But on ssr (8081), the local storage is not available, so the state is empty. So the non-authenticated homepage is rendered via the server first and then when browser.js kicks in, it reloads the correct page.

How can I set the state in SSR and display the correct page first time.

According to docs, I have to create a new store in createReacthandler in server.js and then dispatch the action. I tried it but the action is never dispatched. Also, we already have store created in this same file.

Could you please guide me on the best approach here.

Thanks

One other thing, there is a typo in server.js On line 107 and 306. createNeworkInterface should be createNetworkInterface. Network is missing a "t".

thm-design commented 6 years ago

Check out this line in app.js. This seems to be where you can manipulate store state on the server. https://github.com/reactql/kit/blob/master/src/app.js#L198

klarstrup commented 6 years ago

You can handle this in app.js by reading the cookie in a custom Middleware and dispatching the relevant redux action

thm-design commented 6 years ago

There is also this in the docs: https://reactql.org/docs/state/server what method better?

leebenson commented 6 years ago

Follow the example in https://reactql.org/docs/state/server if you want to do a basic Redux dispatch; follow @klarstrup's cookie-driven approach if you need some way to persist state, and then read that same cookie to determine what needs dispatching on the server.