3

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!

aluuusch
  • 83
  • 2
  • 10
  • Usually you’d use a Boolean variable like that to show a loading indicator while the request resolves. If you aren’t using it why are you adding that variable? – Alexander Staroselsky Jan 29 '22 at 01:41
  • Just a note. set-loading should be triggered right before the backend request, not after. – Arcanus Jan 29 '22 at 01:49

1 Answers1

9

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(.......);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181