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

1 Answer 1

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

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

4 Comments

It works now. But why does it not work with .json() ?
@DarthPlagueris I have updated the code :). Also, async/await increases the code readability. I am a fan of async/await.
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.
I'm glad it helped you. Best wishes for your upcoming interview :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.