Search code examples
reactjsuse-state

Unclear benefit of "setLoading" state in React axios


enter image description here

Hey, could anyone tell me what the state loading does? What do we aim to achieve using the "setLoading(true)" wihtin axios? Thank you!


Solution

  • A loading state is generally used to conditionally render a loading indicator, or similar, while data is being fetched. You can also conditionally hide empty state while it is not populated yet.

    Also, generally you would toggle an isLoading state true immediately prior to making the asynchronous request, setting it back to false when the fetch is complete and you've enqueued a state update.

    const [data, setData] = useState([]); // no data yet
    const [isLoading, setIsLoading] = useState(false);
    
    useEffect(() => {
      setIsLoading(true);
      axios.get("......")
        .then(data => {
          setData(data); // update state with response
        })
        .catch(error => {
          // handle any errors/rejected Promises
        })
        .finally(() => setIsLoading(false)); // complete loading success/fail
    }, []);
    
    if (isLoading) return <Spinner />;
    
    return data.map(.......);