So I have a Json object FriendJson
and in it I have a array field friends
.
Json Object:
[
{
"id": 4,
"updated": "2023-01-07T22:06:23.929206Z",
"created": "2023-01-07T19:49:49.303182Z",
"user": 35,
"friends": [
36,
37,
38,
39
]
}
]
The question is how to access friends
array and traverse it. I am using react so I need to use map()
for traversal. I am trying this in return part of a Functional component, so can use much functionalities of Javascript.
My component:
import React, {useContext, useEffect, useRef, useState} from 'react'
import { useNavigate } from 'react-router-dom';
import AlertContext from '../context/Alerts/AlertContext';
import FriendContext from '../context/Friends/FriendContext';
import FriendItem from './FriendItem'
export default function YourFriends() {
const {friendJson, getFriends, addFriend, getUserId, getReceiverId} = useContext(FriendContext)
const {showAlert} = useContext(AlertContext)
const navigate = useNavigate()
useEffect (() => {
if(localStorage.getItem('authToken')) {
getFriends()
}
else navigate('/signin')
})
return (
<>
<div className="container">
<h2 className="text-center">Your Friends</h2>
{
friendJson.length === 0 && <div className="text-conter">You don't have any friends</div>
}
{
// console.log(friendJson.friends)
friendJson.friends.map((eachFriend) => {
return <FriendItem key={eachFriend} friend={eachFriend}/>
})
}
</div>
</>
)
}
I tried in this way:
friendJson.friends.map((eachFriend) => {
return <FriendItem key={eachFriend} friend={eachFriend}/>
})
But it throws error as:
TypeError: Cannot read properties of undefined (reading 'map')
And when I console.log(FriendJons.friends)
the result is undefined
.