Server side rendering (isomorphic React apps) – Data

Server

We start the server side.

At the GET verb of any url..we already have code where we store initial state in our redux. This time, let’s start it off by fetching data.

We create an initial state object, when store fetched data into an array called repositoryNames. Remember that in order to fetch in Node, we need to either use axios, or node-fetch package.

server.js

Notice thunk. Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the function’s body once the asynchronous operations have been completed.

Once that is done, we create our store, and place it in Provider component. Then place that into StaticRouter within our appMarkup.

This is so that we can inject it into our HTML component.

We then return this HTML component in our response object to the client.

Client Side

We do the same and apply thunk for the client. Since we already have the store and initial app state, it will match up with what the server has.

Before in App.js, where we declare our mapping to props with initialText and changeText handler, we dispatch a very simple Action object with a literal object like so:

which then get passed to reducers/index.js to be processed like so. The initialText is a simple string so we can do this:

But now, we use action objects defined in actions/index.js for more complicated procedures:

Thus, now in Home.js, we declare mapDispatchToProps with the action object getRepositoryNames:

ref – https://reactjs.org/docs/hooks-effect.html

That way, we can use getRepositoryNames inside of Home component. Since Home is a functional component, we use useEffectuseEffect runs after every render!

By default, it runs both after the first render and after every update. Instead of thinking in terms of “mounting” and “updating”, you might find it easier to think that effects happen “after render”. React guarantees the DOM has been updated by the time it runs the effects.

This is the basic case in our example.

Hence we check for props repositoryNames. If its valid, we’ll display it. If it isn’t, we’ll fetch the data so it can be rendered.

Also, useEffect has a nifty feature where it can look at a state variable. If that state changes, it will run the effect. In our case, it would fetch. Hence, I put two use cases of this:

1) value changes after each click. useEffect will run every time the button is clicked because onClick updates value everytime.
2) value changes once after clicks. So useEffect will run the first time, value updates, runs second time, and that’s it.