I am implementing Server side rendering to a react and redux SPA application . So for SSR I fetch data on server and make page by using renderToString method and then on client side I fetch data in useEffect as shown in below example.
Now issue is that after fetching data on server, client is again calling fetchRequestQuery(dispatch) in useEffect. so it is calling same API 2 times which is wrong. I can't remove useEffect as when I navigate page(react router Link) then data should be fetch on client side only for SPA.
So how could I disable api call in useEffect on client side when open page first time but when we navigate page then it should be working normal and make API call in useEffect?
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchRequestQuery } from '../actions';
const loadData = dispatch => (
fetchRequestQuery(dispatch)
);
const Content = () => {
const dispatch = useDispatch();
useEffect(() => {
loadData(dispatch);
}, []);
const { request } = useSelector(state => state);
return (
<span>{JSON.stringify(request)}</span>
);
};
export default {
component: Content,
loadData,
};
import { matchRoutes } from 'react-router-config';
import Routes from './Routes';
import renderer from './helpers/renderer';
import createStore from './store';
const app = express();
app.use(express.static('dist'));
app.get('*', (req, res) => {
const store = createStore();
const { dispatch } = store;
const routes = matchRoutes(Routes, req.path);
const promises = routes.map(
({ route }) => (route.loadData ? route.loadData(dispatch) : null),
);
Promise.all(promises).then(() => {
const content = renderer(req, store);
res.send(content);
});
});
const port = process.env.PORT || 3001;
app.listen(port, () => {
console.log(`Listening on port: ${port}`);
});
I think you can define a variable and set it to true when your component render on client only and , if this variable is true your data while be fetched something like this:
import { useSelector, useDispatch } from 'react-redux';
import { fetchRequestQuery } from '../actions';
const loadData = dispatch => (
fetchRequestQuery(dispatch)
);
const Content = () => {
const initial = useRef(false);
const dispatch = useDispatch();
useEffect(() => {
if(window && initial.current){
// this should run in second render on client
loadData(dispatch);
} else if(window) {
// this should run in first render on client
initial.current = true;
} else{
// this should run on server side
loadData(dispatch);
}
}, []);
const { request } = useSelector(state => state);
return (
<span>{JSON.stringify(request)}</span>
);
};
export default {
component: Content,
loadData,
};