Search code examples
axiosreact-hooksuse-effect

Rerun axios.get in useEffect when url parameter changes


I have been learning React Hooks recently. I have researched for a few days to know how to fetch data and realized that there was axios.

I am using it to fetch data but the problem is it is not working properly when the parameter changes in the url. I have explored tonnes of posts related to this issue here but never got proper ideas.

Here is what I have tried so far. I simplified my code in the link: MyCode.

In my code, when a checkbox value changes, the axios fetches different data.

How can I rerun axios in useEffect when the url parameter changes?


Solution

  • How can I rerun axios in useEffect when the url parameter changes?

    Using a dependency

     useEffect(() => {
        axios.get(`http://myURL/employee_id/${someParam}`).then((response) => {
          setEmployee(response.data);
        });
      }, [someParam]);
    

    Although if I were you I would make the axios call inside changeId function directly. useEffect is overused sometimes. If you can make an action imperatively, there is no need to tie it to a variable and then track it also in useEffect for taking an action.