react-token-auth icon indicating copy to clipboard operation
react-token-auth copied to clipboard

How to store user's info in redux?

Open alexndr-n opened this issue 2 years ago • 0 comments

So I'm working on a project using the library! And the only thing I'm missing is how to get the user's name, email etc. stored into redux for usage across the app. My approach was to decode the JWT token and store it inside the onHydration hook. My code looks like this:

import { createAuthProvider } from 'react-token-auth';
import jwt_decode from 'jwt-decode'
import { useDispatch } from 'react-redux'
import { setName } from '../store/userSlice';

const dispatch = useDispatch()

export const { useAuth, authFetch, login, logout } =
    createAuthProvider({
        getAccessToken: session => session.access_token,
        storage: localStorage,
        onHydratation: (session) => {
            const decoded = jwt_decode(session.access_token)
            console.log('decoded', decoded)
            dispatch(setName('decoded'))
        },
        onUpdateToken: (token) => fetch('/api/refresh', {
            method: 'POST',
            body: token.access_token
        })
            .then(r => {
                r.json().then(a => {
                    if (!a.error) {
                        return a
                    }
                    else
                        logout()
                })
            })
    });

But I am not able to dispatch outside of a react component. What would be the correct approach?

Thanks!

alexndr-n avatar Feb 08 '23 00:02 alexndr-n