javascriptreactjsaxiosstateoptional-chaining

React - Why Optional chaining is not working for this axios request


Im getting this error for the code below:

Uncaught TypeError: Cannot read properties of undefined (reading '0')

I tried to use optional chaining but it's not working...

const [deliveredOrders, setDeliveredOrders] = useState([]);

useEffect(() => {
  const getDeliveredOrders = async () => {
    const res = await axios.get(
      `/api/orders`);
    setDeliveredOrders(res.data);
  };
  getDeliveredOrders();
}, []);

console.log(deliveredOrders?.delivered[0]?.updatedAt);


Solution

  • Because you optional-chained wrong properties, it's delivered which is undefined

    It should be:

    deliveredOrders?.delivered?.[0]?.updatedAt