T-Sajad / football-scores-app

1 stars 0 forks source link

Live data 1: Create a data loader #7

Open josephjclark opened 8 months ago

josephjclark commented 8 months ago

This is one step to getting your app to load live data.

Right now, your app loads data from a JSON file on the file system.

We need to change that to add a component which takes care of loading data for us.

The first step of this is to still return static data, but do it from a Javascript module.

Synchronous Data

Let's start by doing this the easy way. We'll cheat!

  1. Create a module called data-loader.js
  2. That module should import all of the json data in the app into variables
  3. The module should export a function which, when called, returns data by name.

I won't write this in Javascript for you, but here's some pseudo-code to show you what I mean

// data-loader.js

# import standing data from get-standings.json
# import fixture data from get-fixtures-en.json

# declare a function loadData, which takes a single string parameter called "name"
#    if the name is "standings", return standings data
#    if the name is "fixtures", return fixture data
#    do this for all the data your app needs
#   If the name is anything else, anything unexpected, throw an error

# export the loadData function as default

Once this is done, your StandingsList should look a bit more like this:

import dataLoader from './data-loader'

function StandingsList() {
    const standings = dataLoader.get('standings')
}

You can update your other components in the same way.

Asynchronous Data

This is the harder bit.

We haven't talked about asychronous code and promises yet. You should have heard of them. You might want to look up Promises and async/await on MDN. Or we can talk about it of course.

The data loader is going to have to call up to a web server to fetch data to pass to your component. Calling a server should be fairly quick - maybe half a second - but on a slow internet connection it could be several seconds. And what do you do while data is loading?

Javascript won't stop and wait for the server request to complete: it'll issue the request asynchronously (ie, run in the background), and in the meantime continue to execute your code.

You need to make your data loading function asynchronous. So that this works:

function StandingsList() {
    const standings = await dataLoader.get('standings')
}

But there's a catch: you can't do await inside a React component. Not at the top level anyway.

You either have to:

React Suspense was designed for exactly this problem, I recommend you look it up.

So you need to:

1) Make your data loader return a Promise 2) Adjust your component to handle the data loader promise.