Skip to content Skip to sidebar Skip to footer

React Does Not Wait For Server Call To Complete And Throws Error

I have a working rest service that I want to invoke in react. The code does display the list of countries. import {React, useEffect, useState } from 'react' export const Noc = ()

Solution 1:

No. there is no need to introduce any delay/wait. That is already handled by the async/await syntax.

  1. You can either set an initial value in your useState or early return a custom message if nocs is undefined.

  2. If you are fetching from your own api, you can return a response with an error if the fetch request should fail. And then at client side, you can handle that error by wrapping your fetch call inside a try-catch block

import {useEffect, useState } from 'react'

export const Noc = () => {

    const [nocs, setNoc] = useState();

    useEffect(
        () => {
            const fetchNoc = async () => {
                const response = await fetch('http://localhost:8080/countrydefinitions');
                const data = await response.json();
                setNoc(data);
                
            };
            try{
                fetch()
            }catch(error){
                //handle error here
                console.log(error);
            }
        },[]
    );

    if(!nocs){
      return (<p>No NOC found</p>)
    }

    return <div>
     <div>NOC LIST</div>
     {nocs.map(noc => <div>{noc.region}</div>)}
      </div>
}

Solution 2:

React will rerender when the props change. Indeed at the beginning its nothing yet.

2 things to make it more solid can be done.

  1. Add a default value, so that map is available on the array.
const [nocs, setNoc] = useState([]);
  1. And/Or wait until noc is not undefined anymore, and validating that It has a map function, before trying to use map.
{nocs && typeof nocs.map === 'function' && nocs.map(noc => <div>{noc.region}</div>)}

Solution 3:

at first render, nocs has no data then useEffect runs and the second render, nocs will have data. you need to check if nocs is undefined {nocs && nocs.length > 0 && nocs.map(noc => <div>{noc.region}</div>)}


Post a Comment for "React Does Not Wait For Server Call To Complete And Throws Error"