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?
As u can see in the image, it logs multiple times..