2

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ahh I see.. thanks for the article. I didn't know that before
1

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();
  }, []);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.