Home > Mobile >  How can I use the results of an async function inside useEffect?
How can I use the results of an async function inside useEffect?

Time:02-01

I am dispatching an async function inside my useEffect:

  let carts = [];

 useEffect(() => {
    dispatch(getOrder(orderID));
  }, []);

here is my function

export const getOrders = createAsyncThunk("cart/getorders", async () => {
  const response = await axios.get("http://127.0.0.1:8000/techcart/orders/", {
    headers: {
      Authorization: `Token ${token}`,
    },
  });
  return response.data;
});

I want to use the results of this function and put it an array

  order.cart.forEach((element) => {
      carts.push(element);
    });
  

how can i do it after useffect has finished ?

i tried putting it a function inside use effect but it gave the same error cart.foreach is not a function

anyone can help me?

CodePudding user response:

I'm unsure whether you want this to actually happen inside the useEffect. If you wish to preserve the result of your api call in a state variable, you can declare:

const [orders, setOrders] = useState<Order[]>([]);

Then, wrap the getOrder method:

const getOrderWrapper = async (orderId: string) => {
    const orders = await getOrder(orderId);
    setOrders(orders.cart);
}

Then, in your useEffect, you can add the following:

useEffect(() => {
    dispatch(getOrderWrapper(getOrder(orderID)));
  }, []);

CodePudding user response:

If you need to run async code inside useEffect, you can do it like this

useEffect(() => {
  (async () => {
    const response = await dispatch(....)
  })();
}, [])
  • Related