user13069793
user13069793

Reputation:

What would this code look like if instead of "async/await" use "then and catch"?

There is such a method in a React application:

fetchData = async () => {
   try {
    const response = await fetch(`https://........`);
    const data = (await response.json()).group;
    this.setState({
        data: data,
        car: Object.keys(data)[0] 
      },this.filter);
    } catch(err) {
      console.log("404 Not Found");
    }
  };

How to write this part without async / await syntax, and using then and catch?

Upvotes: 0

Views: 46

Answers (4)

Abey
Abey

Reputation: 121

fetchData = () => {
    return fetch(`https://........`)
    .then(response => {
      const data = response.json().group;
      this.setState({
        data: data,
        car: Object.keys(data)[0] 
      },this.filter);
      }).catch(err => {
        console.log("404 Not Found");
       });
   };

response.json() won't return a Promise so you don't need await

Upvotes: 0

Carlos Eustáquio
Carlos Eustáquio

Reputation: 176

If fetch returns a Promise you can:

fetchData = () => {
    fetch(url)
    .then(res => ... )
    .catch(err => ...)
};

Upvotes: 0

emeraldsanto
emeraldsanto

Reputation: 4741

Just like this!

fetchData = () => {
    fetch("YOUR_URL")
        .then(response => response.json())
        .then(json => json.group)
        .then(data => {
            this.setState({
                data,
                car: Object.keys(data)[0] 
            },this.filter);
        })
        .catch(err => {
            console.log("404 Not Found");
        });
}

Upvotes: 2

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

It's simply-

fetchData = () => {
    fetch(url)
    .then(res => res.json())
    .then(data => {
        this.setState({data: data.group, car: Object.keys(data.group)[0]})
    })
    .catch(err => console.log(err));
};

Upvotes: 1

Related Questions