Search code examples
reactjsauthenticationreact-context

Current user with React Context


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.


Solution

  • 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.