Bijay Singh
Bijay Singh

Reputation: 849

useEffect hook dependency not getting updated

I am making an API call inside useEffect hook as follows:

useEffect(() => {
fetchPatientsStartAsync(patientListUrl);
}, [patientListUrl]);

In my code I also have two other state variables and a method as follows:

 const [d, setD] = useState(new Date());
 const [patientListUrl, setUrl] = useState(`${baseUrl}api/patient/list?date=${getDate()}`);

 function getDate() {
  return new Date(d.getFullYear(),d.getMonth(),d.getDate())
 }

I am using a date picker library for updating the 'd' (date). Whenever the date changes I call setUrl and am expecting the useEffect hook to run again. The call goes like this:

    <DatePicker
        onChange={onChange}
        value={d}
        clearIcon={null}
    />
    const onChange = dt => {
     setD(dt);
     setUrl(`${baseUrl}api/patient/list?date=${getDate()}`);
    };

But this is not updating my 'patientListUrl' variable. What is it that am doing wrong here?

I simply want the API call to happen again with the updated 'patientListUrl'.

Upvotes: 1

Views: 1688

Answers (2)

FMCorz
FMCorz

Reputation: 2706

The problem occurs because your state has not yet had the chance to update before you call the getDate function. To remedy this, you could just avoid saving the URL to the state, and constructing it in your effect instead. The dependency to your effect would then be the date itself, like so:

function getDate(d) {
    return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}

const Component = props => {
    const [d, setD] = useState(new Date());

    useEffect(() => {
        const patientListUrl = `${baseUrl}api/patient/list?date=${getDate(d)}`;
        fetchPatientsStartAsync(patientListUrl);
    }, [d]);

    const onChange = dt => {
        setD(dt);
    };

    return <DatePicker onChange={onChange} value={d} clearIcon={null}/>
}

Upvotes: 2

Amit Chauhan
Amit Chauhan

Reputation: 6919

The problem is setD is async function so when you call getDate d isn't updated so you should pass dt to getDate function to get updated URL.

function getDate(dt) {
  return new Date(dt.getFullYear(),dt.getMonth(),dt.getDate())
}
const onChange = dt => {
 setD(dt);
 setUrl(`${baseUrl}api/patient/list?date=${getDate(dt)}`);
};

Upvotes: 2

Related Questions