首页 > 解决方案 > Axios get request returns undefined for the first time in React

问题描述

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..

标签: reactjsaxiosreact-hooksrequest

解决方案


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;

推荐阅读