Reputation: 69
const [urlList, setUrlList] = useState(0);
const callDayList = () => {
console.log(urlList);
Axios.post('http://localhost:3001/api/get', {
passNum: urlList,
});
};
useEffect(callDayList, [urlList]);
<td>
<Link to={"/study/"+item.num}
onClick={function() {
setUrlList(item.num);
// num = item.num
}}
>{item.title}</Link>
</td>
this code is sending a state, which is urlList to backend, and I have some problem.
as I studied about useEffect, it executes only if the urlList changes its value. but when I click a url, it keep passes the initial value of urlList, which is 0.
to check urlList changes correctly, I changed Link in to "/", and saw the outcome of console.log(urlList) in callDayList, when I click, it shows correct value of state, but if set back the Link, and click, the value of the urlList is still initial value and send it to backend.
callDayList has to be execute when the urlList changes it's value, I can't figure out why it keep passes initial value of the state.
Upvotes: 0
Views: 61
Reputation: 10512
useEffect
will run the first time it is set up as well as when anything changes.
If you want to avoid this initial run, you can try using a useRef
variable to track whether it's the first run:
import { useState, useRef, useEffect } from 'react';
const isFirstRun = useRef(true);
const callDayList = () => {
if (isFirstRun.current) {
isFirstRun.current = false;
return;
}
// do your effect
Axios.post('http://localhost:3001/api/get', {
passNum: urlList,
});
return () => { isFirstRun.current = true; }
};
useEffect(callDayList, [urlList, isFirstRun]);
It looks cumbersome, but should get you the behaviour you require. If you end up needing to skip useEffect's initial run in more than one place in your code, it'd probably be worthwhile extracting this behaviour into a custom hook.
Upvotes: 2