Search code examples
javascriptreactjsreact-reduxreact-hooksuse-effect

ensuring that axios api call finishes for props before rendering child component


I have the code below:

function StoryCarousel(props) {
    const [ivrDests, setIVRDests] = useState([]);

    useEffect(() => {
        async function getIVRDests() {
          var data = {
            "customer-id": customer_id
          };
          let response = await axios.post(`http://localhost:2000/files/get-ivr-dests`, data)
          //let response = await axios.post(`/files/get-files`, data)
          setIVRDests(response.data)
        }
        getIVRDests() 
        
    }, []);

  return (
    <div className="StoryCarousel">
        <StoryCarouselItem ivr_dests={ivrDests} options={props.options} />
    </div>
  );
}

This code works sometimes as in the api call will finish in time and then successfully pass the data to the child component as a prop. However, sometimes, the api call is not finished which means that ivr_dests does not have a value which screws with my child component. Is there anyway I can make it so that ivrDests must be populated before launching the storycarouselitem?

Thanks


Solution

  • This should work:

    function StoryCarousel(props) {
        const [ivrDests, setIVRDests] = useState([]);
    
        useEffect(() => {
            async function getIVRDests() {
              var data = {
                "customer-id": customer_id
              };
              let response = await axios.post(`http://localhost:2000/files/get-ivr-dests`, data)
              //let response = await axios.post(`/files/get-files`, data)
              setIVRDests(response.data)
            }
            getIVRDests() 
            
        }, []);
    
      return (
        <div className="StoryCarousel">
            {ivrDests.length != 0 && <StoryCarouselItem ivr_dests={ivrDests} options={props.options} />}
        </div>
      );
    }
    

    You can also use a custom hook (or get a library that provides one, such as https://react-query.tanstack.com/) and then have a loading flag.