Home > Software design >  How to set data to the state after fetching from backend?
How to set data to the state after fetching from backend?

Time:01-24

I want to get data from the backend and want to set those data to the state in ReactJS. Here is my source code

const [eachAsset, setEachAsset] = useState([]);
function ShowModalView(id)
    {
        
            
            axios.get("http://localhost:8070/assets/detail/" id).then((res)=>{
                
                const data = res.data
                setEachAsset(data)
                //console.log(eachAsset);
            }).catch((err)=>{
                
                console.log(err.message);
            })
        
        
        setShow2(true);
        
        
    }

When I uncomment the console log, it shows an empty array. It means, setEachAsset(data) does not work properly. But I want to store data that are getting from the backend to the eachAsset state. What is the problem of this source code?

CodePudding user response:

setEachAsset([...data])

I hope this would work

CodePudding user response:

I would recommend using async-await which makes the code easier to read and understand the flow of the program as compared to promise chains.


const [eachAsset, setEachAsset] = useState([]);

const ShowModalView = async (id) => {
    try {
        const resp = await axios.get("http://localhost:8070/assets/detail/" id);
        setEachAsset(resp.data)
        console.log(resp.data);
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }
    setShow2(true);
}


  •  Tags:  
  • Related