Home > Blockchain >  Manage current user using context and custom hooks in React
Manage current user using context and custom hooks in React

Time:03-02

I would like to implement two methods: login and logout. I'm trying to share the current user's data using context so I can get those details from any component.

In my App component I'm using the useUser custom hook and sharing its methods and properties with the UserContext.Provider.

const { currentUser, setCurrentUser, logout, login } = useUser() 

Then, in my useUser custom hook:

 function useUser () {
        const [ currentUser, setCurrentUser ] = useState(null)
        const navigate = useNavigate()

        function mapUserProperties ({ _id, first_name, last_name, email, isAdmin }) {
            return {
                _id, 
                first_name,
                last_name,
                email,
                isAdmin,
            }
        }

        const login = (token) => {
            localStorage.setItem('token', token)

            const userData = mapUserProperties(jwtDecode(token))
            setCurrentUser(userData)
            navigate('/', { replace: true  })
        }

        const logout = () => {
            localStorage.removeItem('token')
            setCurrentUser(null)
            navigate('/', { replace: true })
        }

        return {
                currentUser, 
                setCurrentUser, 
                login,
                logout
            }
    }

The logout function works fine, when I click the button it removes the jwt token from the localstorage, sets the current user to null and redirects. Also the navbar shows the login and register buttons, meaning that the state changed.

Unfortunately when I use the login function, the token is stored in the localstorage and the location is redirected, but the state is not showing that the currentUser data has changed.

I'm using react dev tools, with the logout function it updates instantly, but with the login it does not.

If I use F5 and refresh the state variable (currentUser) has the data updated, meaning it has to do with rendering, but why does it update with logout ? what am I missing ?

CodePudding user response:

set currentUser default value

  const [ currentUser, setCurrentUser ] = useState(mapUserProperties(jwtDecode(localStorage.getItem('token'))))

will help you.

Check you this bioiler plate code for more understaning.

https://github.com/AvaniBataviya/react-boilerplate/blob/master/src/hooks/useAuth.js

CodePudding user response:

In the loginForm component I was using the useUser custom hook. Instead I should've used the user Context to get the login function from the parent component. Now everything works as expected.

  • Related