Francis
Francis

Reputation: 11

How to create a loader page for a react component that is fetching data from an api

Id like to create a loader component that is displayed on the screen before data being fetched from an API is rendered. The data received has many links and with those links include pictures, when the data is loaded there's a split-second where images are not shown and the layout of the page is disrupted, So id like to create a component that is rendered on the page and is removed when all assets and data from the API is loaded. IDK maybe there's a better approach to this I'm open to any suggestions. Ps: the data isn't all loaded at the same time, so a loading page that would be rendered before the whole page is rendered wouldn't work since the data isn't all fetched at the same time.

Ive attached a component which shows how the data is being rendered into the page which dynamically adds cards to the page. I think this is the best place to place a loader spinner until all assets have been loaded

import AlbumCard from "../Cards/AlbumCard"

const AlbumsList = (props) => {
    return (
        <ul
      style={{
        position: "relative",
        padding: "0",
        display: "flex",
        flexWrap: "wrap",
        width: "100%",
      }}
    >
      {props.item.map((item) => (
        <AlbumCard
          id={item.id}
          key={item.id}
          image={item.picture}
          artist={item.name}
          title={item.title}
        />
      ))}
    </ul>
    )
}

export default AlbumsList

Upvotes: 0

Views: 312

Answers (1)

obido
obido

Reputation: 31

I'm not sure if I understand you correctly but maybe it will help you.

The first thing you should do is to create "loading component" that will be shown when data is fetching. It can be simple spinner for example.

Then you can implement it like this:

const [loading, setLoading] = useState(false);

const fetchingFunction = () => {
  setLoading(true); // setting loading to true
  // simple example of fetch
  fetch(SOME_URL)
    .then(do something with your fetched data)
    .then(() => setLoading(false)) // data is fetched so change loading to false
 }

return (
  { loading ? <LoadingComponent /> : <ComponentThatShowsFetchedData /> } // loading is your state and we check if it's true then we render loading component but when it changes to false, then we render data

Upvotes: 2

Related Questions