Axios get request returns undefined for the first time in React

Viewed 2368

I am using DRF for creating the api.. I am able to fetch the data using axios, but it returns undefined the first time and hence, when I use useState, it gets set as undefined..

ItemDetail.js:

import React, { useState, useEffect } from 'react'
import axios from 'axios'
const ItemDetail = () => {


    const [detail, setDetail] = useState('')

    const [id, setId] = useState('')



    const RecipeDetail = async () => {

        const res = await axios({
            method: 'get',
            url: `http://127.0.0.1:8000/api/recipe-detail/1`,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                "Access-Control-Allow-Origin": "*",
            }

        })

        setDetail(res.data)

    }

    useEffect(() => {
        RecipeDetail()

    }, [id])

    console.log(`Hi ${detail}`)


    return (
        <div>
            Hi
        </div>

    )
}

export default ItemDetail

So why is the API returning undefined for the first time? I read few answers regarding the use of async/await which I have.. Also, when I console.log(detail), it logs it multiple times.. Why is that so? enter image description here As u can see in the image, it logs multiple times..

3 Answers
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const ItemDetail = () => {
  const [detail, setDetail] = useState('');

  const RecipeDetail = async () => {
    const res = await axios({
      method: 'get',
      url: 'http://127.0.0.1:8000/api/recipe-detail/1',
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': '*',
      },

    });

    setDetail(res.data);
  };

  useEffect(() => {
    RecipeDetail();
  }, [detail]);

  console.log(`Hi ${detail}`);

  return (
    <div>
      {detail ? 'Hi' : 'Loading ... '}
    </div>

  );
};

export default ItemDetail;

You are trying to access or log the detail before it is set ,means that useEffect will be called after your content is rendered so console.log(Hi ${detail}); ran first and undefined was logged , later useEffect ran and RecipeDetail(); data received state changed as you called setState. and rerender occured again and this time you received value.

When it was first rendered, no API response was received yet. and then, when second rendered, API resonse was receiced.

Related