Issue
How I can use data from my first fetch in second fetch ? I am getting undefined for the first search and then it's ok, how I can get it on first search without getting "undefined"?
const [summoner, setSummoner] = useState("");
const [playerData, setPlayerData] = useState({});
const [playerRank, setPlayerRank] = useState({});
function searchPlayer(event) {
axios.get("API1" + summoner + API_KEY).then(function (response) {
setPlayerData(response.data);
}).catch(function (error) {
console.log(error);
});
console.log(playerData.id);
axios.get("API2" + playerData.id + API_KEY).then(function (response) {
setPlayerRank(response.data)
}).catch(function (error) {
console.log(error);
});
}
This is my console:
log: undefined
log: id
Solution
I recommend you to use something like useEffect
to handle fetching data in react. Not sure what event
is used for, but looked unused so if that's the case you can do the following:
const [summoner, setSummoner] = useState("");
const [playerData, setPlayerData] = useState({});
const [playerRank, setPlayerRank] = useState({});
function getPlayerData() {
axios.get("API1" + summoner + API_KEY).then(function (response) {
setPlayerData(response.data);
}).catch(function (error) {
console.log(error);
});
}
function getPlayerRank() {
if(!playerData.id) return;
axios.get("API2" + playerData.id + API_KEY).then(function (response) {
setPlayerRank(response.data)
}).catch(function (error) {
console.log(error);
});
}
useEffect(() => {
getPlayerData()
}, [])
useEffect(() => {
getPlayerRank()
}, [playerData])
This setup will trigger the getPlayerRank
function any time playerData
changes. If event
is used in either request, you want to pass that into the dependency array as well so you would end up with
useEffect(() => {
getPlayerData(event)
}, [event])
useEffect(() => {
getPlayerRank()
}, [playerData])
https://reactjs.org/docs/hooks-effect.html
Answered By - DannyMoshe
Answer Checked By - - Robin (ReactFix Admin)