reactjsaxiosreact-hooksuse-effectreact-fullstack

React useEffect returns empty array after fetching data with axios


I'm trying to fetch my data from an api I created, but it always returns an empty array.

Here's my code

const [orders, setOrders] = useState([]);

  const getOrders = async () => {
    try {
      const access_token = localStorage.getItem("access_token");
      let result = await axios({
        method: "GET",
        url: "http://localhost:3000/orders/open",
        headers: {
          access_token,
        },
      });
      setOrders(result.data);

      console.log(result.data);
      console.log(orders);
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    getOrders();
  }, []);

This is the console result from my browser enter image description here

As you can see, result.data successfuly returns 2 objects inside of it, but after I add it on order state with setOrders(result.data), order is still empty.

I've also tested the API on Postman and there's no problem at all. enter image description here

I've been doing get data with axios this way and this is my first time having this problem.


Solution

  • It's because Reactjs's Batching State Update mechanism

    Your state update is asynchronously so it won't be updated until the function/event is finished.

    Check for console.log(orders) right before your return() function.