1

I am trying to fetch data from an api which should return a json object with an array of recipes. I am using React hooks on the front end and Axios to perform the request. The hook runs but I get an error while trying to access the json array from the response.

Here's the sample api response:

{
    count: 30,
    recipes: [objects, ... 29]
}

and my code to get the recipe response:

const fetchRecipes = async () => {
    try {
        const recipeData = await Axios.get(api);
        console.log(recipeData);
        const recipes = await recipeData.json(); // error occurs here
        setRecipes(recipes);
        setLoading(false);
    } catch (err) {
        console.log(`Error occurred fetching recipes ${err}`)
    }
};

useEffect(() => {
    fetchRecipes();
}, []);

I have removed the hooks declarations and api url is https://api.myjson.com/bins/t7szj. The problem lies in getting the array from the response. Is there something wrong with my api call?

This is the error message:

Error occurred fetching recipes TypeError: recipeData.json is not a function
Darth Plagueris
  • 339
  • 4
  • 20

1 Answers1

1

Did you try this?

const fetchRecipes = async () => {
    try {
        const recipeData = await Axios.get(api);
        console.log(recipeData.data);
        const recipes = recipeData.data;
        setRecipes(recipes);
        setLoading(false);
    } catch (err) {
        console.log(`Error occurred fetching recipes ${err}`)
    }
};

you don't have to call res.json() on the response when using axios (unlike fetch) because axios handles that for you automatically. Meaning that axios parses the response to JSON by default.

async/await with Axios

blueseal
  • 2,726
  • 6
  • 26
  • 41
  • It works now. But why does it not work with .json() ? – Darth Plagueris Nov 12 '19 at 09:43
  • @DarthPlagueris I have updated the code :). Also, `async/await` increases the code readability. I am a fan of `async/await`. – blueseal Nov 12 '19 at 09:51
  • 1
    Okay, thanks so much for your explanation. I am brushing up after a month ill and wanted to cover my basics then learn some more before attending interviews. This was definitely a good tip sir. Much appreciated. – Darth Plagueris Nov 12 '19 at 09:53
  • 1
    I'm glad it helped you. Best wishes for your upcoming interview :) – blueseal Nov 12 '19 at 09:56