I want the state ‘user’ in the component ‘Home’ as below: The console.log is working fine and is not undefined. But the ‘map’ loop gives me an error “TypeError: Cannot read property ‘map’ of undefined”
import {UserContext, UserProvider} from './context/UserContext' const Home = () => { const [user, setUser] = useContext(UserContext) console.log(user) return( <div className="css-home"> <div className="css-home-div-find"> <input className="css-home-find" placeholder="Typo here to find someone" type="text"/> </div> <div className="css-overflow css-home-friends"> { user.friends.map(friend => ( <FriendsSummary/> )) } </div> </div> ) }
In the console.log(user), i have it:
{ "user": [ { "_id": "6045352a4eb4f70ff41b0f73", "date": "2021-03-07T20:18:45.893Z", "name": "Shrek", "email": "[email protected]", "hate": "Corn", "friends": [ { "_id": "6045352a4eb4f70ff41b0f74", "name": "Donada", "hate": "skol", "voted": false, "votes": { "heart": 10, "heartbroken": 2, "fire": 130, "horse": 12, "eye": 12412 } }, { "_id": "6045352a4eb4f70ff41b0f75", "name": "Otto", "hate": "it", "voted": false, "votes": { "heart": 1, "heartbroken": 2, "fire": 2, "horse": 12, "eye": 123 } } ], "__v": 0 }]}
My useContext is that:
useEffect(() => { getUser() },[]) const[user, setUser] = useState({}) const getUser = async () => { const response = await fetch('http://localhost:8081/users/get_friends') const data = await response.json() setUser(data.user[0]) } return( <UserContext.Provider value={[user, setUser]}> {props.children} </UserContext.Provider> )
I think that it can be some asynchronous problem, but I dont know how to solve it…
Answer
Issue
Your initial state doesn’t have a friends
array to map for the initial render before data has been fetch and state updated.
const[user, setUser] = useState({});
Solution
Provide valid initial state. The initial state should include any nested initial state that is referenced on the initial render. If your UI is mapping a user.friends
array then it needs to be available to do so.
const[user, setUser] = useState({ friends: [], });