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.
CodePudding user response:
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>
))}
CodePudding user response:
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>
))}