Proptypes always gives error no matter if the value is correct

Asked

Viewed 46 times

3

I’m using the React (16.11.0) with Proptypes (15.7.2) and Hooks.

And I have a component that receives an object with some data from the database. Testing the data using the console.log:

{ console.log('Carousel reciving: ', typeof informations, informations) }

Print the following message:

Carousel reciving:  object (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

Data is sent to the component by calling:

<Carousel informations={informations} isLoading={isLoading} />

Component:

const Carousel = ({ informations, isLoading }) => (
    <ReactPlaceholder ...algumas props />...algum contúdo</ReactPlaceholder>
) // Carousel

But it doesn’t matter if I change the Proptype to vector or object, it keeps giving the following error:

Warning: Failed prop type: Invalid prop informations of type array supplied to Carousel, expected object.

If I change to PropType.object.isRequired, the error says that the given value is of type array. What if I change to PropType.array.isRequired, the error says that the given value is of the object type:

Carousel.propTypes = {
    informations: PropTypes.object.isRequired,
    isLoading: PropTypes.bool.isRequired,
} // propTypes

I know I could use the function of fetch within the component, but this data is shared with other components.

1 answer

3


Although, in Javascript, the type of an array is object, Proptypes does not consider an array as an object.

Demonstration:

console.log(typeof {});
console.log(typeof []);

In your case, it looks like you’re passing a object array to the property informations. So in your PropTypes, you must declare that you want to validate an object array.

Thus:

Carousel.propTypes = {
  //                      ↓↓↓↓↓↓↓           ↓↓↓↓↓↓
  informations: PropTypes.arrayOf(PropTypes.object).isRequired,
  // Outras propriedades...
}

I added a demonstration in the Codesandbox.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.