Search code examples
gatsbynetlifyjamstack

Persisting api data on client after fetching at build time with gatsby and netlify


New to Gatsby and Netlify but I have a question that I can't find answer to elsewhere, possibly because it's the wrong approach.

I'm building a weather app for a client that needs to show an animated view of the last day/week/months data which requires making multiple requests to the weather API for the data at different resolutions and then plugging that into the visualisations with a setInterval essentially.

Rather than making all these requests on the client, it occurred to me, I could get all the data at build time with a scheduled build and serve the page statically with this updated data each day which would save hammering the API and reduce costs.

The problem is gatsby assumes you want to generate html with fetched data and use createPages but here I just want to store the data as json in the js bundle for rendering on the client.

Is there a way to put the build time fetched and formatted data into json or similar and serve statically for rendering on the client?


Solution

  • You tagged this question with the jamstack tag and your approach fits exactly into this approach.

    Is there a way to put the build time fetched and formatted data into json or similar and serve statically for rendering on the client?

    Yes.

    1. Build your React code that shows the weather data.
    2. Build your weather data json.
    3. Use only variables from your weather data json.

    Simple example:

    import data from "./data/weatherData.json"
    
    const WeatherApp = () => {
      return (
        <Layout>
          <h1>{data.title}</h1>
          <div>{data.rain}</div>
          <div>{data.temperature}</div>
        </Layout>
      );
    };
    

    In order to populate the weather data you could build a complicated GraphQL query that fetches all the data exactly the way you need it.

    One other approach would be to build your own API for example with AWS lamba or similar serverless free service and serve your weather data with that. This way you would not need to trigger the gatsby build.