skip to Main Content

How we can set loading in react

I tried using usestate but I don’t work
I want to set loading while getting data from api
Before getting data I set

const {loading, setloading} = useState (false)
const getdata = () => {
  setloading (true);
  fetch();
}

2

Answers


  1. Check this snippet below:

    import React, { useState, useEffect } from 'react';
    
    function YourComponent() {
      const [loading, setLoading] = useState(false);
    
      const getData = () => {
        setLoading(true);
        // Simulate API call delay with setTimeout
        setTimeout(() => {
          // Fetch data here
          setLoading(false);
        }, 2000); // Replace 2000 with actual API call
      };
    
      useEffect(() => {
        getData();
      }, []); // Empty dependency array to run the effect only once
    
      return (
        <div>
          {loading ? (
            <p>Loading...</p>
          ) : (
            <div>
              {/* Display your data here */}
            </div>
          )}
        </div>
      );
    }
    
    export default YourComponent;
    
    
    1. I imported useState and useEffect from the React module.
    2. I added a useEffect hook to call the getData function when the component mounts. The dependency array [] ensures that the effect runs only once, similar to the behavior of componentDidMount in class components.
    3. Inside the getData function, I used setLoading(true) to indicate that data is being fetched. After simulating an API call with setTimeout, I used setLoading(false) to indicate that the data has been fetched and loading is done.
    4. In the component’s return, I used the loading state to conditionally render either a loading message or your data content.

    Remember to replace the setTimeout function with your actual API call using a library like fetch or axios.

    Login or Signup to reply.
  2. You could initialize the component in a loading state, then update the loading variable to be false within the callback of your fetch call.

      const [loading, setloading] = useState(true);
    
      fetch("https://myapi").then( (value: Response) => {
        // No longer loading
        setloading(false);
    
        // Do something with response value
      });
    

    It would be a good idea to wrap your fetch call within useEffect so it only runs on component load.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search