Current user with React Context

Viewed 3690

I want to have a way to get and fetch the current user using React Context (to not pass props to all my components)

I tried using React Context but didn't understand how I would achieve something like const { currentUser, fetchCurrentUser } = useCurrentUser() from the docs.

2 Answers

here is what i did for my project:

// src/CurrentUserContext.js
import React from "react"

export const CurrentUserContext = React.createContext()

export const CurrentUserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = React.useState(null)

  const fetchCurrentUser = async () => {
    let response = await fetch("/api/users/current")
    response = await response.json()
    setCurrentUser(response)
  }

  return (
    <CurrentUserContext.Provider value={{ currentUser, fetchCurrentUser }}>
      {children}
    </CurrentUserContext.Provider>
  )
}

export const useCurrentUser = () => React.useContext(CurrentUserContext)

and then use it like this:

setting up the provider:

// ...
import { CurrentUserProvider } from "./CurrentUserContext"
// ...

const App = () => (
  <CurrentUserProvider>
    ...
  </CurrentUserProvider>
)

export default App

and using the context in components:

...
import { useCurrentUser } from "./CurrentUserContext"

const Header = () => {
  const { currentUser, fetchCurrentUser } = useCurrentUser()

  React.useEffect(() => fetchCurrentUser(), [])

  const logout = async (e) => {
    e.preventDefault()

    let response = await fetchWithCsrf("/api/session", { method: "DELETE" })

    fetchCurrentUser()
  }
  // ...
}
...

the full source code is available on github: https://github.com/dorianmarie/emojeet

and the project can be tried live at: http://emojeet.com/

If useContext returns undefined, then you might have forgotten the Provider or need to move your provider up the stack.

U dont explained what u want to do with the data but...After u exec the function fetch in use effect. Now u have the object user in the state currentUser. Try to console log after the use effect the currentUser and see what dat inside it. After u can use it with currentUser."whatever prop inside"..

Related