'React axios getting a null / undefined result
Can some go through my code and see what is the mistake I have done.
React and Axios code
import React, { useState, useEffect } from "react";
import { useParams, Outlet } from "react-router-dom";
import axios from "axios";
export default function Agent() {
const [Agent, setAgent] = React.useState();
const agentid = useParams();
React.useEffect(() => {
axios.get(`https://valorant-api.com/v1/agents/`).then((res) => {
setAgent(res.data);
});
}, []);
console.log(Agent);
return (
<div>
<h1>{agentid.agentid}</h1>
</div>
);
}
Can someone explain why there is an undefined?
Solution 1:[1]
Axios already returns a data property, and with the api doing that aswell it will end up being like this:
setAgent(res.data.data);
It will display undefined at first because of the API call being asynchronous, hereby not instantly, so when the API has returned your response you're setting a state which causes the component to re-render, hence run the console.log again, and anything outside the useEffect.
Solution 2:[2]
The first undefined is expected.
You are waiting for the promise to resolve when you call the API but meanwhile React continues rendering the Component. After the Promise resolves, the callback is executed, which changes the state with the data from the API. When the state changes, the whole component re-renders and you can see a second console.log with the actual data.
Solution 3:[3]
set default value to your state const [Agent, setAgent] = React.useState({}); i'm set default state as empty object. you can write as you expected mock object
use effect hook will call after component is initial render. that's why first log is undefined.
Solution 4:[4]
Axios.get is an asynchronous call. It'll take some time to fetch the data from the api. Until then, "Agent" is undefined. This call asynchronous, JavaScript does not wait for "Agent" to get defined, hence you see the "undefined" log.
Later, as soon as the data reaches the client from the Api through Axios, setstate is called in your code and everything is re-rendered. Hence you see the data printed this time.
So, you didn't do any mistake. This is an expected behavior.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicolai Christensen |
| Solution 2 | Fernichter |
| Solution 3 | Dev.Dilan |
| Solution 4 | Labnan |
