Home > Enterprise >  createContext, useContext returns undefined
createContext, useContext returns undefined

Time:06-07

The code when I console.log(user) it returns undefined when it should return this... [{ id: 1, name: 'username' }] .

I don't know what is causing it to do so, if you have any idea please tell me anything I can do, maybe there are updates to the useContext thing, if so, please inform me. Thanks in advance!!

import {createContext, useState} from 'react'

const UsersContext = createContext()

export const UsersProvider = ({children}) => {
    const {user, setUser} = useState([{
        id: 1,
        name: 'username'
      }])

    return <UsersContext.Provider
    value={
        {user}
    }>{children}</UsersContext.Provider>
}

export default UsersContext



// The next File...

import UserItem from "./UserItem"
import {useContext} from 'react'
import UsersContext from "../context/UserContext"

function userList({handleDelete}) {
  const {user} = useContext(UserContext)

  return (
    <div>
        {console.log(user)}
    </div>
  )
}


export default UserList

End of code...

CodePudding user response:

import {createContext, useState} from 'react'
const UsersContext = createContext(null)

export const UsersProvider = ({children}) => {
    // useState returns an array not object
    // if you want to store one user, use an object
    const [user, setUser] = useState({id: 1,name: 'username'})
    // if you want to store mutiple users
    const [user, setUser] = useState([{id: 1,name: 'username'}])

    return <UsersContext.Provider value={{user}}>
            {children}
           </UsersContext.Provider>
}

export default UsersContext



// The next File...

import UserItem from "./UserItem"
import {useContext} from 'react'
import UsersContext from "../context/UserContext"

function userList({handleDelete}) {
  const { user } = useContext(UserContext)

  return (
    <div>
        // if you used an object
        {user?.username}
        // for array of objects
        {user && user.map((user, i) => (<p key={i}>{user.username}</p>))}
    </div>
  )
}


export default UserList

CodePudding user response:

The First thing you want to check is, make sure the UserList component are wrapped with UserProvider

  • Related