so I am running into a slight problem with using React and its hooks. I am trying to print out an array from an API, but it first prints as an empty array to the console, and then only when I click the button again does it prints the array.
Here is the function I'm using to make the array from API Data:
const getChampion = () => {
for(let i = 0; i < getData.length; i ){
let individualChamp = champPeep.current.value;
if(getData[i].Name === individualChamp){
// console.log(getData[i]);
setShowChampion(individualChamp);
setChampionTitle(getData[i].Title);
let hitPoints = getData[i].Hp
let attack = getData[i].Attack;
let defense = getData[i].Defense;
let attackRange = getData[i].AttackRange;
let armor = getData[i].Armor;
setRadarData([hitPoints, attack, defense, attackRange, armor]);
console.log(radarData) //returns empty array don't know why
}
} //! Have to click search twice to update array to new array
} //Get Champion name and check to see if it is found in the API
Here is the button the input field that I assigned to this function:
return(
<div>
<div className='search'>
<input ref={champPeep} type="search" id='champion-search' placeholder='e.g Annie' />
</div>
<button onClick={getChampion} className='btn-prim'>Search</button>
</div>
)
And this is what is being logged to the console when I click on button btn-prim
:
[]
And when I click the btn-prim
button again this is then logged (which is correct):
(5) [524, 2, 3, 625, 19]
Is there something I'm doing wrong? Please help!
T.I.A
CodePudding user response:
setState
is asynchronous in react, so when you try to log radarData
immediately after setRadarData
it displays previous data stored in radarData
. You can use useEffect hook to log current radarData
state
useEffect(() => {
console.log(radarData)
}, [radarData])
why React setStates are async : Why is setState in reactjs Async instead of Sync?
CodePudding user response:
I suggest that instead of you using
console.log(radarData) //returns empty array don't know why
try to add useEffect
hook to log the value of radarData
whenever it changed
Use something like:
useEffect(() => {console.log(radarData)}, [radarData])
CodePudding user response:
State updates will reflect in their next re render and not immediately. This has already been solved.
Basically your
setRadarData([hitPoints, attack, defense, attackRange, armor]);
console.log(radarData) //returns empty array because its still using the default state {}.
Refer to useState set method not reflecting change immediately