Title: react setstate works on second click
Tags: reactjs
Question: Hello i'm having an issue i don't know why but the setState doesn't work properly on the &quot;first click&quot;
i have these states
const [selected,setSelected] = useState(&quot;&quot;);
const [fetched,setFetched] = useState([]);
when i click on a div i set the selected state first then the fetched with the data i fetch like this
const selectStuff = async (data) =&gt;{
setSelected(data);
const response = await fetch(someurl);
if(response !== undefined)setFetched(response);
the setfetched doesn't get executed, i have to click on the element a second time for the state to re render, i'm always having this issue when i use multiple setState on the same funcion can someone tell me why? I can't find any answer
Comment: You should perform your side effect (the fetch) using the useEffect hook. https://reactjs.org/docs/hooks-effect.html

Comment: where does `someurl` come from?

Comment: someurl is just a string like "/saveStuff" i just put someurl to keep it generic



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:04/11/21', 'FavoriteCount': 0.0, 'PostTypeId': 1, 'Tags': '<reactjs>', 'Title': 'react setstate works on second click', 'ViewCount': 81, 'id': 67050580, 'user_AboutMe': None, 'user_AccountId': 20147206.0, 'user_DisplayName': 'robeert', 'user_Reputation': 85.0, 'user_Views': 21.0, 'user_id': 14775441.0}}