skip to Main Content

Im trying to render a loading Spin while the fetch is running but the component is not rendering.

let spinning: boolean;

...

<Button htmlType="submit" onClick={() => spinning = true}>
   {spinning ? <Spin /> : <></>}
</Button>

2

Answers


  1. You’ve overlooked the most fundamental part of React in every React tutorial… state. Just updating a variable doesn’t trigger a component to re-render. Updating state does:

    const [spinning, setSpinning] = useState(false);
    
    ...
    
    <Button htmlType="submit" onClick={() => setSpinning(true)}>
       {spinning ? <Spin /> : <></>}
    </Button>
    
    Login or Signup to reply.
  2. If you want to trigger a loading boolean state when the component is fetching something from the API, the best approach would be to first create a state with useState hook.

    Then in your fetch logic, you should set the state to true, and after the fetch is done, set it back to false.

    // ... code
    const [loading, setLoading] = useState(false);
    
    async function getData() {
      setLoading(true);
      try {
        //... your fetch logic
      catch {
        //... error handling
      finally {
        setLoading(false);
      }
    }
    
    return (
      <Button htmlType="submit" onClick={() => getData()}>
        {spinning ? <Spin /> : <></>}
      </Button>
    )
    
    
      
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search