Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 141751

How is this fetch optimised on react gatsby website

$
0
0

On the front page of a website served with a Gatsby React setup I have a NavbarExtra component that shows some data via an api. The data coming from that endpoint changes several times a day.

The idea now is now to optimize the fetch so the fetch is made as seldom as possible so the api is used as rearly as possible, it has a limit to it(different paid plans).

The scenario should be that as long as the user has entered the site the fetch will only happen at once. Then the user can go around the site maybe close even the component with the fetch and again go back to the front-page where the fetch is made.

Now the component is called in the navmenu if the user is only on the front page: {isLandingPage && <NavBarData/>} and in that component there is this fetch:

useEffect(() => {
    fetch(
      'https://endpoint',
      {
        method: 'GET',
        headers: {
        },
      }
    )
      .then(response => {
        if (response.status >= 200 && response.status <= 299) {
          return response.json();
        }
        throw Error(response.statusText);
      })
      .then(data => {
        const { result } = data.quoteResponse;
        setNumbers(result));
      })
      .catch(error => {
        console.log(error);
      });
  }, 0);

Firstly I would like to ask for how should this fetch be done so the api is used as rearly as possible, so the user gets the recent data and only gets it again when for example reloading the page?

Secondly I understand some concepts about single page apps and static site generators as here the used Gatsby, and probably have understood it right that if I would like to use the fetched data on different pages(even other pages than the isLandingPage) of the website I could just use it in one component that is served on different pages and it would not refetch on each page enter?


Viewing all articles
Browse latest Browse all 141751

Trending Articles