William Mandang
William Mandang

Reputation: 133

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.

Upvotes: 2

Views: 2313

Answers (2)

Jemika Negara
Jemika Negara

Reputation: 64

look like you do console.log before state update, try adding setTimeout or console.log outside function like this

const [orders, setOrders] = useState([]);
  // you can console.log here after state update
  console.log(orders)

  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);
  
  setTimeout(() => {
    // or wait for 100ms until orders state updated
    console.log(orders);
  }, 100);
} catch (err) {
  console.log(err);
}
  };

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

Upvotes: 1

Ryan Le
Ryan Le

Reputation: 8412

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.

Upvotes: 2

Related Questions