英文:
How to get token from localstore to redux store when i refresh the app or restart the app in react native
问题
我试图将令牌存储在本地存储中,并在用户打开应用程序时尝试获取令牌值,但是在使用redux-toolkit中获取应用程序时,我得到了undefined。请有人帮我解决这个问题。
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { User, LoginPayload, LoginPayloadError } from './interface';
import { login } from '../../service/authService';
import AsyncStorage from '@react-native-async-storage/async-storage';
let savedToken;
const getData = async () => {
savedToken = await AsyncStorage.getItem('token');
};
getData();
console.log(savedToken);
const initialState: User = {
token: savedToken ? savedToken : '',
id: 0,
email: '',
nicename: '',
firstName: '',
lastName: '',
displayName: '',
role: '',
loading: false,
error: '',
};
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {},
extraReducers: builder => {
builder.addCase(login.pending, (state, action) => {
state.loading = true;
}),
builder.addCase(login.fulfilled, (state, action) => {
const saveToken = async () => {
await AsyncStorage.setItem('token', action.payload.token);
};
saveToken();
return {
...state,
loading: false,
...action.payload,
};
}),
builder.addCase(login.rejected, (state, action) => {
return {
...state,
loading: false,
error: action.payload,
};
});
},
});
export default userSlice.reducer;
<details>
<summary>英文:</summary>
**I am trying to store the token in local store and try to get token value when the user open app but i get undefined while getting the app in redux-toolkit anyone please help me with this**
import {createSlice, PayloadAction} from '@reduxjs/toolkit';
import {User, LoginPayload, LoginPayloadError} from './interface';
import {login} from '../../service/authService';
import AsyncStorage from '@react-native-async-storage/async-storage';
let savedToken;
const getData = async () => {
savedToken = await AsyncStorage.getItem('token');
};
getData();
console.log(savedToken);
const initialState: User = {
token: savedToken ? savedToken : '',
id: 0,
email: '',
nicename: '',
firstName: '',
lastName: '',
displayName: '',
role: '',
loading: false,
error: '',
};
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {},
extraReducers: builder => {
builder.addCase(login.pending, (state, action) => {
state.loading = true;
}),
builder.addCase(login.fulfilled, (state, action) => {
const saveToken = async () => {
await AsyncStorage.setItem('token', action.payload.token);
};
saveToken();
return {
...state,
loading: false,
...action.payload,
};
}),
builder.addCase(login.rejected, (state, action) => {
return {
...state,
loading: false,
error: action.payload,
};
});
},
});
export default userSlice.reducer;
**I have to define SavedToken for storing the token and try to get the value from the getData function. if the console.log(inside the getData then i will get the token value but if the console out the function i will get undefined**
</details>
# 答案1
**得分**: 0
也许你应该以不同的方式做。我不了解你的项目结构,但我认为你可以在你的 App.js 中做一些类似以下的事情:
```JavaScript
// 在任何操作之前获取并保存令牌
useEffect(() => {
const getData = async () => {
const token = await AsyncStorage.getItem('token');
// 将令牌保存到 Redux 存储中
setUser({token});
};
getData();
}, []);
你可以阅读这个有趣的链接 Authentication flow 和 实现恢复令牌的逻辑。
英文:
Maybe you should do it differently.
I don’t know your project structure but I think you could do something like that in your App.js
// get and save token before anything
useEffect(() => {
const getData = async () => {
const token = await AsyncStorage.getItem('token');
// save the token to the redux store
setUser({token});
};
getData();
}, []);
You can read this interesting link Authentication flow and Implement the logic for restoring the token
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论