Unable to send api response data from express to react after refreshing the page

Issue

I’m learning react and node js with express framework and I’m working on a project where I need to retrieve API data from express to react.

I retrieved data from backend express js where I made a simple json value. My backend server.js code is given below.

server.js

const express = require('express')
const app = express()
const PORT = 3001;


app .get('/api/contents',(req,res)=>{
    const contents=[
        {
            "id":0,
            "heading":"Joshua Tree Overnight Adventure",
            "content":"A sight in the blue sea..."
        },
        {
            "id":1,
            "heading":"Catch waves with an adventure guide",
            "content":"Lorem.."
        },
        {
            "id":2,
            "heading":"Catch waves with an adventure guide",
            "content":"Lorem epsum ..."
        }
    ];
    res.json(contents)
})
app.listen(PORT,()=>{
    console.log("express server is running...")
})

In react app, I used axios to retrieve those values from backend and tried to pass the api values of content with id= 0 as props in "TheLatestArticles" component. I have updated proxy in package.json in react to connect backend. The below code is the mainhomepage component where it is enclosed with TheLatestArticles component with props value

MainHomePage.js


import axios from 'axios';
import {useState,useEffect} from 'react'

function MainHomePage(){

    const [content,setContent]=useState([]);

    useEffect(()=>{
        const fetchPosts = async ()=>{
            const res =await axios.get("/api/contents")
            setContent(res.data)
            console.log(res)
        }
        fetchPosts()
    },[])
    return (
        <>
        <TheLatestArticle content={content} />
        </>
       );
}

export default MainHomePage;

TheLatestArticle.js

import cardImage from "./../../Images/card.jpg"
import './TheLatestArticleCard.css';
const TheLatestArticleCard=(props)=>{
    console.log(props)
    return(
        <>
        <div className="card">
            <div className="image">
                <img src={cardImage} alt="cardimg"/>
            </div>
            <div className="content">
                <p className="heading">{props.content.heading}</p>
                <p className="body-content">{props.content.content}</p>
            
            <div className="details">
                <p className="details-info">Travel <span className="details-info-2">/ August 21 2017</span></p>
            </div>
            </div>
        </div>
        </>
    )
}
export default TheLatestArticleCard;

When I run the application, It displayed all the api values in the screen given below.
enter image description here

I console.log the api values inside useEffect and it displayed all the api values perfectly.

enter image description here

But when I refresh the page, the api value became undefined and gave me this errorenter image description here

Can you please solve me this issue with the reason behind this error? Thanks a lot!

Solution

Try it like this

{(content && content.length > 0) && <TheLatestArticle content={content} />}

Since your API call is async there won’t be any data in content initially. After a while, your API is called and data is fetched. Then you will have data. To prevent TheLatestArticle to blow up we add some conditions when to show that component. The error in the screenshot is when you try to use a property heading from content where content is empty.

Now with the condition, TheLatestArticle will not render until there is some data.

Update

You are using <TheLatestArticle content={content} /> and content is assumed to be an object. But as per your code, it’s an array. If you are not already using content.map((c)=> <TheLatestArticle content={c} />) you should do that.

Answered By – Sanish Joseph

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published