JamesJavascript
JamesJavascript

Reputation: 49

React - prop .isRequired

I'm getting this warning

Failed prop type: The prop queryObjState.isRequired is marked as required in RefineSearchBar, but its value is undefined.

Why is the prop required, I haven't got isRequired in propTypes.

Any help would be great, Thanks!

export default function RefineSearchBar({ travelAdvisorApi, queryObjState }) {
  const dispatch = useDispatch();
  const [formData, setFormData] = useState({
    location: '',
    coordinates: {
      latitude: 0,
      longitude: 0,
    },
    radius: 5,
    priceLevel: '',
  });
  console.log(queryObjState);
  const setLocationResponse = (location, coordinates, radius = 5) => {
    setFormData((prev) => ({
      ...prev, location, coordinates, radius,
    }));
  };
  const submitForm = () => {
    if (!formData.coordinates.latitude && !formData.coordinates.longitude) {
      return;
    }
    dispatch(setSearchQueries(formData));
    travelAdvisorApi(formData);
  };

  return (
    <div className="sidebar w-100 d-flex justify-content-evenly align-items-start py-2">
      <HandleAutocomplete
        setLocationResponse={setLocationResponse}
        queryLocation={queryObjState.location}
      />
      <Container fluid>
        <Button type="button" onClick={submitForm}>
          Refine Search
        </Button>
      </Container>
    </div>
  );
}

RefineSearchBar.propTypes = {
  travelAdvisorApi: PropTypes.func.isRequired,
  queryObjState: PropTypes.shape(PropTypes.any),
};
RefineSearchBar.defaultProps = {
  queryObjState: {
    location: '',
    coordinates: {
      latitude: 0,
      longitude: 0,
    },
    radius: 5,
    priceLevel: '',
  },
};

Upvotes: 2

Views: 234

Answers (1)

Japsz
Japsz

Reputation: 785

According to this issue in prop-types the error shows up when you pass anything other than a javascript Object to PropTypes.shape(...).

You can omit it using PropTypes.any directly

RefineSearchBar.propTypes = {
  travelAdvisorApi: PropTypes.func.isRequired,
  queryObjState: PropTypes.any,
};

But if you want to define the prop correctly then you have to give a valid javascript object to PropTypes.shape with each subattribute and its validation with PropTypes:

RefineSearchBar.propTypes = {
  travelAdvisorApi: PropTypes.func.isRequired,
  queryObjState: PropTypes.shape({
    location: PropTypes.string,
    coordinates: PropTypes.shape({
      latitude: PropTypes.number,
      longitude: PropTypes.number,
    }),
    radius: PropTypes.number,
    priceLevel: PropTypes.string,
  }),
};

Upvotes: 2

Related Questions