Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(React) Correct way to typecheck array of objects that may be empty?

I have a prop that is usually an array of objects, but sometimes (including on the component's first render) the array is empty. I know that using PropTypes.array is frowned upon and I should use PropTypes.arrayOf() instead, but if I use PropTypes.arrayOf(PropTypes.object), there is a failed prop type warning due to the empty state of the array. What is the correct way to type check this prop?

like image 658
Joon Park Avatar asked Dec 14 '16 02:12

Joon Park


People also ask

How do you check if an array is empty or not?

To check if an array is empty or not, you can use the .length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

How do you check if an array of objects is empty in JavaScript?

Having confirmed that the variable is an array, now we can check the length of the array using the Array. length property. If the length of the object is 0, then the array is considered to be empty and the function will return TRUE. Else the array is not empty and the function will return False.

How do you empty an array in JavaScript?

Assigning the array to an empty array is the quickest method of emptying an array in JavaScript. In javascript, length is a property that, when set to 0, clears the array. splice() method can be used to delete 1 or more elements from the array in JavaScript.

How do you create an empty object in JavaScript?

Can you create an empty object JavaScript? Objects can also be created using the new keyword. With the built-in Object Constructor in Javascript, new creates an empty object; or, this keyword can be used with a user-defined constructor function: with builtin Object Constructor .


1 Answers

You shouldn't be getting an error unless you set isRequired on it. That is,

myArray: PropTypes.arrayOf(PropTypes.object).isRequired

This will require an array but not necessarily an object. It's how you would handle exactly the case you mention where initially you may pass an empty array.

like image 127
ZekeDroid Avatar answered Sep 19 '22 00:09

ZekeDroid