0

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>
)
3
  • What is your response variable value? Commented Jan 24, 2021 at 23:26
  • The first block of code is the response Commented Jan 24, 2021 at 23:30
  • just use a regular fetch instead of axios. unless you're intercepting any requests or making pre and post flight confligs then you really dont need axios. fetch('http://example.com/api/courses').then(r => r.json()).then((response) => { setCourseDetails(response); } ) Commented Jan 25, 2021 at 0:00

1 Answer 1

2

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.

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

6 Comments

He could also use optional chaining with the nullish coalescing operator for when the properties of his object do not exist yet.
Does the current configuration of CRA compile that down to es5 yet?
Thanks for your response, I was able to output the message, but when I tried to output value in data object I got this error response "Error: Objects are not valid as a React child (found: object with keys {id, course_code, course_name, slug, course_fee, duration, start_date, end_date,}"
@GabrielGeelario you may want to ask a separate question about this if you continue to struggle with it as it's a different issue, but that error indicates you are trying to render an object directly. From your error it appears you are now directly rendering your data object.
@tmdesigned honestly I don't know and wouldn't want to give a (guess) of an answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.