1

I have two API endpoints that I am retrieving data from and I want to display the number of records in each. This is my code so far, which sort of works, and test6tg5ing the API in Postman returns the correct data -

const [orders, setOrders] = useState([]);
useEffect(() => {
  const fetchData = async () => {
    const resSeven = await axios('http://localhost:5000/api/7daycheck');
    const resThirty = await axios('http://localhost:5000/api/30daycheck');
    setOrders({ seven: resSeven.data, thirty: resThirty.data });
    };
    fetchData();
}, []);

Now, When I add console.log(orders.seven); , the console shows this -

Console output

So when I add the line <p>{orders.seven.length}</p> in my JSX code it throws the error "TypeError: Cannot read property 'length' of undefined". What's going on?

1
  • First of all, you initialize orders as an array (const [orders, setOrders] = useState([]);) then set it to an object (setOrders({ seven: resSeven.data, thirty: resThirty.data });); it does not make a lot of sense. Anyway, the issue is due to the fact that orders.seven is undefined until you get back the response from your fetch call. If you change <p>{orders.seven.length}</p> with <p>{orders && orders.seven && orders.seven.length}</p> you should not see that error anymore. Commented Jan 28, 2021 at 14:40

1 Answer 1

2

The initial state of orders is an empty array:

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

Which has no property called seven. So when you try to display that state:

<p>{orders.seven.length}</p>

You'll get an error. If the resulting value for orders isn't an array then you shouldn't set it to one to begin with. Give it the structure you expect:

const [orders, setOrders] = useState({ seven: [] });

This would initialize it to an object with a property called seven which itself is an empty array. Then the length will correctly be 0.

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

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.