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

7k views Asked by At

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?

1

There are 1 answers

0
ZekeDroid On BEST ANSWER

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.