Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to store user's info in redux? #34

Open
alexndr-n opened this issue Feb 8, 2023 · 0 comments
Open

How to store user's info in redux? #34

alexndr-n opened this issue Feb 8, 2023 · 0 comments

Comments

@alexndr-n
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant