Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Emma Groves
Emma Groves
716 Points

React: componentDidMount firing before user input

I am create a book list app where users input the name of their favourite books. Once the user has entered the book into the form / input the below function should take that input and then make the api call with that input value. My problem is that the below code runs before the users have input anything.

Please help?

  componentDidMount(search) {
    const url = `https://www.googleapis.com/books/v1/volumes?q=${
      this.state.userInput
    }`;
    fetch(url)
      .then(response => response.json())
      .then(data => this.setState({ books: data.items[0].volumeInfo }))
      .catch(error => error);
  }

1 Answer

tomd
tomd
16,701 Points

Thats because componentDidMount runs when the component is mounted. You'll need to move everything inside the componentDidMount function to another function that gets called when the user clicks 'submit' and hook up the submit button to the function

onClick(e){
// code from componentDidMount here
// You'll need to switch out `this.state.userInput` to `e.target.value` or something similar.
}



render (
    return (
         // form code here
        <button onClick={this.handleClick}></button>
    );
);

or you can use a submit handler on the form itself