Liichi / CocktailFinder

0 stars 0 forks source link

Try/Catch - Async/await y no .then .catch #10

Closed Pablo14697 closed 4 years ago

Pablo14697 commented 4 years ago

https://github.com/Liichi/CocktailFinder/blob/c68fe20764f880d2de5694162be56d30b6c6af5c/src/actions/search.ts#L83

Evitar el uso de .then o .catch. Podrias reemplazarlo por const response = await fetch(...); const data = await response.json() es lo mismo y mucho mas corto Usar try{} catch{} para capturar el error.

Liichi commented 4 years ago

Arreglado

Pablo14697 commented 4 years ago

        const response = await fetch(Config.API_URL+searchText);
        if(!response.ok)
            return dispatch(fetchErrorAction()); //EN ESTE MOMENTO QUE HAY UN ERROR DEBERIA EXISTIR LA FUNCION `throw new Error("message")` asi es enviado al catch y este lo captura
        const resData : any = await response.json();
        let searchResult : CocktailData[];
        if(resData === undefined)
            return //RETURN NO DEVUELVE NADA? De ultima se podria omitir o no? 
        if(resData.drinks == null){
            searchResult = [];
        }else{
            searchResult = resData.drinks.map((cocktail) =>{
                return {thumbURL: cocktail.strDrinkThumb,name: cocktail.strDrink,id: cocktail.idDrink}
            });
        }
        //update redux data
        dispatch(successFetchAction(searchText,searchResult));
    }catch(error){
        dispatch(fetchErrorAction()); //No le pasas el parametro "catcheado" por el catch
    }