Reputation: 127
I want to update state of tickerList
variable, with the data.ticker
i tried doing like setTicker(data.ticker)
but this doesn't change state of tickerList
variable
how to do this?
const [tickerList, setTickerList] = useState([]);
fetch('/ticker').then(res => res.json()).then(data => {
setTickerList(data.ticker) // here i want to assign data.ticker to tickerList
console.log(data.ticker) // prints list of strings
console.log(tickerList) // prints empty list
})
update 1
useEffect(()=>{
fetch('/ticker').then(res => res.json()).then(data => {
setTickerList(data.ticker)
})
console.log(tickerList)
},[tickerList])
by doing as above, /ticker
endpoint is getting called infinitely
any way to avoid that?
update 2
const handleClick = () =>{
fetch('/ticker').then(res => res.json()).then(data => {
setTickerList(data.ticker)
})
}
Upvotes: 0
Views: 85
Reputation: 1109
for some performance purposes, setState actions are Async in react, that's mean the js engine will not wait for updating of state and next lines will be executed. that's why you get an empty list!
in your case, after re-rendering, you can access to the new state value and use it in UI.
take a look at this example:
round 1:
const [state, setState] = React.useState(0);
React.useEffect(() => {
setState((prev) => prev + 1); // 0 + 1 = 1
console.log("State Value", state); //result: 0
}, []);
round 2:
React.useEffect(() => {
setState((prev) => prev + 1); // 1 + 1 = 2
console.log("State Value", state); //result: 1
}, []);
EDIT (a problem in code): your useEffect will runs continuously because every time you change the tickerList
and tickerlist
is one of the useEffect
dependencies.
Upvotes: 1
Reputation: 706
In react, state changes are implemented asynchronously, so if you log the state immediately after the change - you wouldn't see it.
Beside, you should make the fetch inside useEffect
hook, or inside componentDidMount
.
to see the state change you can do something like that:
useEffect(()=> console.log(tickerList) ,[tickerList])
Upvotes: 1