Search code examples
javascriptreactjstypesprop

React - (nested) prop type is invalid; it must be a function


my console logs the following when I start my app:

Warning: Failed prop type: Home: prop type home is invalid; it must be a function

I have looked online but have not seen any cases or examples of a nested prop-type returning this error so am struggling to correct the warning, here is my code:

Home.propTypes = {
  home: {
    readyStatus: PropTypes.string,
    list: PropTypes.arrayOf(PropTypes.object),
  },
  fetchUsersIfNeeded: PropTypes.func,
};

Home.defaultProps = {
  home: () => {},
  readyStatus: '',
  fetchUsersIfNeeded: () => {},
};

Any help or advice is appreciated - thank you in advance!


Solution

  • I think the problem is in the way things are written

    Home.propTypes = {
      home: PropTypes.shape({
        readyStatus: PropTypes.string,
        list: PropTypes.arrayOf(PropTypes.object).isRequired,
      }),
      fetchUsersIfNeeded: PropTypes.func,
    };
    
    Home.defaultProps = {
      home: {
        list: [],
        readyStatus: '',
      },
      fetchUsersIfNeeded: () => {},
    };
    

    This first solution makes both the type similar as an object and it should work. Other option could be:

    Home.propTypes = {
      home: PropTypes.func,
      fetchUsersIfNeeded: PropTypes.func,
    };
    
    Home.defaultProps = {
      home: () => {},
      fetchUsersIfNeeded: () => {},
    };
    

    Here we make the prop type as a function so that the type at both the instance matches.

    A quick tip if the home is an object which is a state then it should be an object like solution 1 or if the home is a computed value which is derived from other states or network call or anything then you should use the function.

    You could also look into flow.org if you want better type checking for functions.

    Note, I've not tested this code but it should solve the issue.