react admin useGetIdentity只返回全名,id未定义化身未定义



我的应用程序基于React管理教程和作为后端的环回4

我正在尝试获取登录用户的id,登录机制运行良好,但当我尝试访问登录用户的id时,它仍然未定义。

在我的authProvider中,我的登录功能是

login: ({ username, password }) => {
const request = new Request(
process.env.REACT_APP_API_URL + '/users/login',
{
method: 'POST',
body: JSON.stringify({ email: username, password }),
headers: new Headers({ 'Content-Type': 'application/json' }),
},
);
return fetch(request)
.then((response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then((auth) => {
localStorage.setItem(
'auth',
JSON.stringify({ ...auth, fullName: username }),
);
})
.catch(() => {
throw new Error('Network error');
});
},

我把它用在一个组件中:

const CurrentUserId = ({ id }) => {
const { identity, isLoading: identityLoading } = useGetIdentity();
console.log(identity);
if (identityLoading) {
return <span>Loading...</span>;
} else {
// find the user_id from the identity
const user_email = identity.fullName;
const user_id = identity.id;
return <span>id: {user_id}</span>;
}
};

但是I console.log返回

{id: undefined, fullName: 'xxx@xxxxx.com', avatar: undefined}

我遵循了这里的指示https://marmelab.com/react-admin/AuthProviderWriting.htmlhttps://marmelab.com/react-admin/useGetIdentity.html

知道如何检索id吗?

非常感谢

如果您从服务器接收到JWT令牌,则需要对其进行解码并按如下方式存储:

import jwtDecode from 'jwt-decode' 
...
function saveLBToken({ token } : { token: string }) {
const decoded = jwtDecode(token) 
if (decoded && typeof decoded === 'object') { 
sessionStorage.setItem(LB4_TOKEN, JSON.stringify({ token, ...decoded })) 
} else {
console.log('Bad LB token:', decoded)
}
}

感谢MaxAlex的回答,我最终在代码中使用了这个:

export const authProvider = {
// authentication
login: ({ username, password }) => {
const request = new Request(
process.env.REACT_APP_API_URL + '/users/login',
{
method: 'POST',
body: JSON.stringify({ email: username, password }),
headers: new Headers({ 'Content-Type': 'application/json' }),
},
);
return fetch(request)
.then((response) => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then((auth) => {
const { id, name, email, exp, iat } = jwtDecode(auth.token);
if (!id || !name || !email || !exp || !iat) {
throw new Error('Invalid token');
}
if (exp < iat) {
throw new Error('Token expired');
}
localStorage.setItem(
'auth',
JSON.stringify({
...auth,
id,
fullName: name,
email,
exp,
iat,
}),
);
})
.catch(() => {
throw new Error('Network error');
});
},

相关内容

  • 没有找到相关文章

最新更新