2017-10-18 16 views
0

Comment puis-je modifier le code suivant en syntaxe asynchrone?Modifier la récupération en syntaxe asynchrone

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}`); 
      }); 
} 

J'ai essayé de le faire comme ceci:

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

et je reçois l'erreur suivante: Erreur de syntaxe: C:/Users/EYAL/web/fe/réagir/airbnb/src/Homes/index.js: await est un mot réservé (17:14)

+0

attendre res.json()? ou peut-être que res.json() ne renvoie pas la promesse –

Répondre

1

Vous devez déclarer la méthode componentWillMount comme async afin d'utiliser await. Vous pouvez le faire en changeant la signature:

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

également .json est une méthode de sorte qu'il devrait être res.json(). (Merci bennygenel)

+2

'.json' est une méthode donc il devrait être' res.json() '. Peut-être que vous devriez ajouter cela aussi – bennygenel