How to prevent component form rendering till the API is fetched [duplicate]


Description:

  1. API has data in form of an array that has 3 elements in it [in form of an object].
  2. The data being fetched is passed as parameters to the child component.

Parent Component

function App() {
  const [details, setDetails] = useState([]); // api data in form of array consisting objects
  const [isLoading, setIsLoading] = useState(true); //To display losing on screen till the api arrives
  const [isError, setIsError] = useState(false); // To display error if api fails to arrive
  const [index, setIndex] = useState(0); // it defines the index of array arriving through api

  //fetching the api

  const getData = async () => {
    const resp = await fetch(url);
    if (resp.status >= 200 && resp.status <= 299) {
      let data = await resp.json();
      setIsLoading(false);
      setDetails(data);
    } else {
      setIsError(true);
    }
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    <>
      <section className='heading-container'>
        <h1 className='main-heading'>Job Experience</h1>
      </section>
      <Button />
      <Info details={details[index]} />
    </>
  );
}

  1. When the index is 0 and data is fetched I started working on my child component as I saved the code everything was good but, when I manually changed the index from 0 to 1 or 2 the app crashed giving the error TypeError: Cannot destructure property ‘company’ of ‘details’ as it is undefined.

Child Component

import React from "react";

const Info = ({ details }) => {
  const { company, title, dates, duties } = details;
  return (
    <section className='info-container'>
      <h4>{title}</h4>
    </section>
  );
};

export default Info;

Question:

I think the error is because the data isn’t fetched yet but the child component <Info/> is asking for it because it wants to get rendered.

so is there any way I can delay the rendering of the child component until the API arrives with the data in the parent component?

Source: JavaSript – Stack Overflow

November 13, 2021
Category : News
Tags: fetch-api | javascript | react-component | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.