Home > Enterprise >  Why useEffect is working twice even if I change the data?
Why useEffect is working twice even if I change the data?

Time:04-14

I try to call a method in service class from MainPanel with useEffect hook:

Here is my MainPannel:

function MainPanel() {

  const [customers, setCustomers] = useState([]);
  

  useEffect(() => {
    const getCustomers = async () => {
      const customers = await getCustomerList();
      setCustomers({ customers });
      console.log(customers)
    };
    getCustomers()
  }, []);

  return (
    <div className="App">
      {/* do something */}

    </div>
  );
}

export default MainPanel;

And here is the service method that I called from useEffect:

export async function getCustomerList() {

    axios.get("http://localhost:8080/customer", { params: { id: 1 } })
    .then(response => console.log(response.data))
}

In this scenario useEffect is working but working twice and console.log is printing twice (2 times log correct value and 2 times undefined).

If I just get the data with return statement instead of printing to console like

export async function getCustomerList() {

    axios.get("http://localhost:8080/customer", { params: { id: 1 } })
    .then(response => {return response.data})
}

Same thing happening but this time response is coming as undefined. I know they are separate problems but I just need to understand a proper way of fetching data and use it in useEffect only once.

How can I achieve it ?

CodePudding user response:

You should add return in your function getCustomerList.

export async function getCustomerList() {
    return axios.get("http://localhost:8080/customer", { params: { id: 1 } });    
}

And get data like the following:

      const res = await getCustomerList();
      setCustomers({ res.data.customers });

CodePudding user response:

Probably React.StrictMode is firing the useEffect twice as for returning the values you should probably just do as the other answer ( @Liki Crus) suggests

  • Related