1

Hey guys I am trying to pass a command in a prop to child component from a parent. The thing is that after my button is clicked a state in parent component has to be changed for intended sidebar to open. I seem to not get it right with the .then() part at the end on the onClick function, as I get error: × Unhandled Rejection (TypeError): Cannot read property 'then' of undefined

CHILD COMPONENT:

return (
          <div
            className="results-item"
            onClick={async () => {
              let place_detail;
              try {
                const URL = `https://maps.googleapis.com/maps/api/place/details/json?place_id=${places.place_id}&fields=name,rating,formatted_phone_number&key=
      MYAPIKEY`;
                const response = await axios.get(URL);
                console.log(response.data);
                place_detail = response.data.results;
              } catch (error) {
                console.log(error.message);
              }

              this.setState({ place_detail }).then(this.props.sideBarOpen);
            }}
          >
            <ResultsItem
              name={places.name}
              image={Thumbnail}
              rating={places.rating}
              rating_total={places.user_ratings_total}
            />
          </div>
        );

PARENT COMPONENT:

<Search sideBarOpen={() => setOpen(!open)} />
Adam Schwarcz
  • 437
  • 1
  • 4
  • 14
  • Does this answer your question? [Can I execute a function after setState is finished updating?](https://stackoverflow.com/questions/34687091/can-i-execute-a-function-after-setstate-is-finished-updating) – rickdenhaan Apr 25 '20 at 15:05

2 Answers2

0

setState doesn't return a promise. Use a callback instead:

this.setState({ place_detail }, () => {
   this.props.sideBarOpen();
});
kind user
  • 40,029
  • 7
  • 67
  • 77
0

You can't use .then on setState call. You can use callback function of setState to what you are trying to do -

this.setState({ place_detail }, () => this.props.sideBarOpen());
Atin Singh
  • 3,624
  • 2
  • 18
  • 25