user6517334
user6517334

Reputation:

Cannot read property Redux object

I think I have a really basic question. So on my index page, I have an input field that I take the number. According to this number I display my component which is on the next page. And I am storing them with Redux. So for example, if the user enters 3, on the next page I display the component 3 times. Everything is quite okay, I am getting the list successfully, which is showing the number of displays. But at the first time, I am getting Cannot read property 'order_number_of_display' of undefined which means if the page is rendered again, everything is working okay.

Anyway here how I get the number of display:

const newOrderList = useSelector((state) => state.newOrderList);
  const { newOrder } = newOrderList;
  const numberOfDisplay = newOrder.order_number_of_display;

And for the first time, it is undefined on my console but in Redux store, it is actually fulfilled. Could you give me a hint on how I can fix it?

Also, this is how I am displaying:

{
        Array.from({ length: numberOfDisplay }, (v, i) => ( 
<Component/>
)
}

enter image description here

Upvotes: 0

Views: 41

Answers (1)

Shyam
Shyam

Reputation: 5497

Your newOrderList might not be an object ( may be null ) or it might be just an empty object. So there are 2 ways to fix this

  1. Guard your newOrderList by setting default values
    const newOrderList = useSelector((state) => state.newOrderList);
    const { newOrder = {} } = newOrderList || {};
    const numberOfDisplay = newOrder?.order_number_of_display || 0
  1. Set the initial value in the store for the state newOrderList in your reducer

Upvotes: 1

Related Questions