1

How can I change the following code to async syntax?

componentWillMount(){
 fetch('http://localhost:9000/api/homes')
          .then( response => {
              if(response.ok) {
                  return response.json();
              }
              throw new Error('Network response was not ok.');    
          })
          .then( data => {
              this.setState({
                  originalList:data,
                  displayedList: data
              });
          }
        )
          .catch( error => {
              console.error(`fetch operation failed: ${error.message}`);
          });
}

I have tried to do it like this:

componentWillMount(){
  const res = await fetch('http://localhost:9000/api/homes');
  const json = await res.json;
              this.setState({
                  originalList:json,
                  displayedList: json
              });
}

and I get the following error: Syntax error: C:/Users/EYAL/web/fe/react/airbnb/src/Homes/index.js: await is a reserved word (17:14)

1
  • 1
    await res.json()? or maybe res.json() does not return promise Commented Oct 18, 2017 at 12:03

1 Answer 1

4

You have to declare the componentWillMount method as async in order to use await. You can do that by changing the signature:

async componentWillMount() {
  const res = await fetch('http://localhost:9000/api/homes');
  const json = await res.json();
  this.setState({
    originalList: json,
    displayedList: json
  });
}

Also .json is a method so it should be res.json(). (Thanks bennygenel)

Sign up to request clarification or add additional context in comments.

1 Comment

.json is a method so it should be res.json(). Maybe you should add that as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.