Volear
Volear

Reputation: 119

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.

Upvotes: 0

Views: 178

Answers (2)

DariushStony
DariushStony

Reputation: 173

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>
))}

Upvotes: 0

Mina
Mina

Reputation: 17234

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>
    ))}

Upvotes: 1

Related Questions