Reputation: 237
I am trying to output a single value of an object but am getting null. Don't know where I got it wrong. Below is the JSON response I got but when I tried to display it, am geting null ;
{
"success": true,
"message": "Course Retrieved Successfully.",
"data": {
"id": 1,
"course_code": "null",
"course_name": "Greatness",
"slug": "greatness",
"course_fee": 10,
"duration": "10hours",
"start_date": "2000-09-08",
"end_date": "2000-09-08",
}
}
My code below
const [coursedetails, setCourseDetails] = useState([])
const init =()=>{
axios.get('http://example.com/api/courses').then(response => {
setCourseDetails(response);
}).catch(error =>{
console.log('error',error)
})
}
useEffect(() => {
init();
}, []);
return (
<div>
{coursedetails.data.course_name}
</div>
)
Upvotes: 0
Views: 86
Reputation: 2254
When axios gives you a response to a GET request, the data returned from the server is in a data
property. This is a bit confusing in your example, because the data returned from the server also has a data
property. So, in effect, you need to access response.data.data
. You might adjust when you set the course details to instead have setCourseDetails(response.data);
However, you also have some mismatched types. Your coursedetails
starts as an array, but you then set it to an axios response, which is an object. So you'll want to change that to useState({})
or something similar.
Your JSX return value (at least, I presume it is. It's not wrapped in a return statement, but perhaps you deleted some for consciseness.) also presumes that there is always a data
property on coursedetails
, and a course_name
property on that data
property. This isn't true, for instance, at the beginning. You will want to adjust this to check for its presence, i.e. {coursedata.data && coursedata.data.course_name ? coursedata.data : ''}
Finally, it is helpful to track the status of async requests like this. I often use a separate state for the status, i.e. const [status,setStatus] = useState('init');
Then right before the axios request is fired, setStatus('loading')
and then right after it is successful, setStatus('success')
. (And, if there's an error, setStatus('error')
. This makes it easier to show different loading states to the user.
Upvotes: 2