Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
Cannot read properties of undefined (reading 'map') with REST response

I'm novice in React and have problem with map. My react component

const NewsComponent = () => {
const params = useParams()
const pk = params.pk
const [news, setNews] = useState([])

useEffect(() =>{
    const getNews = async() => {
        await httpClient.get(`/feed/${pk}`)
            .then((response) => {
                setNews(response.data);
            })
    }
    getNews();
}, [])

return(
    <div>
        {news.results.map((post, index) =>(
            <div>
                <h1>{post}</h1>
            </div>
        ))}
    </div>
)
}

My response from backend:

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "title": "asdasd",
            "text": "asdasdasd",
            "likes": [],
            "dislikes": [],
            "attachments": []
        }
    ]
}

But it doesn't work.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

news state on as initial value as array and you need to use it as an object.

const [news, setNews] = useState({})

Also, in the html you need to check if results is not undefined.

{news.results?.map((post, index) =>(
        <div>
            <h1>{post}</h1>
        </div>
    ))}
about 4 years ago · Juan Pablo Isaza Report

0

There are several issues with your code

The first one is the API response!

It's an object, not an array, but you left the initial value of the state as an empty array.

const [news, setNews] = useState({});

The second thing is that there is no data in the initial rendering, so there is no result in the news state, that's why it gives you an error. To solve this, you can use optional chaining.

{news.results?.map((post, index) =>(
    <div>
        <h1>{post}</h1>
    </div>
))}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!