Getting data from external API before render

1.6k views Asked by At

I have an application based on the React Starter Kit.

Every page have a fetch function that getting data from API in componentDidMount lifecycle.

I want to get data first and then render page with data and return it to the client. UX in my case no matter.

I know that RSK is isomorphic, I'm ready to change boilerplate or create my own. But I do not understand how to fetch data from API before render page(I mean how to tell express server what data requires).

How App fetching data now:

example_page.js:

import getBooks from 'queries/getAllBooks';
...
class IdTag extends React.Component {
componentDidMount(){
    this.getBooks();
}

  getBooks() => {
    const request = getBooks();
    request
      .then(...)
  }
}

getAllBooks.js:

import doGet from './doGet';

let result = '';

const request = async () => {
  const reqUrl = '/api/books/';

  result = await doGet(reqUrl);

  return result;
};

export default request;

doGet.js:

const request = async reqUrl => {
  let requestResult = null;

  const doQuery = async () => {
    const response = await fetch(reqUrl, {
      method: 'GET',
    });
    const result = await response.json();
    result.status = response.status;

    return result;
  };

  requestResult = await doQuery();
  return requestResult
}
... 
export default request;

server.js:

...
app.get('/api/*', async (req, res) => {
  const newUrl = config.gate.URL + req.url.replace('/api', '');
  const accessToken = req.cookies.access_token;

  const response = await nodeFetch(newUrl, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });
  const result = await response.json();

  res.status(response.status);
  res.json(result);
});
...
2

There are 2 answers

1
Thomas N On

You could simply set a flag when you begin your fetch, and while it's fetching return null instead of rendering. Something like:

flag = true;
request = getBooks();
request.then(flag = false);

and then:

render(){
  if (flag){
    return null;
  } else {
    return this.view;
  }
}
1
manoj bellamkonda On

If each page has api calls, then Its better to use redux and redux saga. Purpose of redux saga is to handle api calls. It will process the actions in a Q. The moment u call api using fetch method, create below actioncreators

1) InitialLoading(true) 2) Fetch api call action creator 3) Based on success, error create action creator to store fetch method output data in store 4) InitialLoading(false)