我有一个 Next.js 应用程序,对于状态管理,我使用 Redux Toolkit。现在,为了维护前端的身份验证状态,我需要获取现有令牌并将其发送到后端进行验证。如果我从后端获得成功响应,那么我想使用
{isAuthenticated: true}
else {}
初始化我的 Redux 存储。我怎样才能实现这样的目标。
我探索了其他选择,但似乎没有什么能提供令人满意且有效的答案。
// Redux Slice - authSlice.js
import { createSlice } from '@reduxjs/toolkit';
export const authSlice = createSlice({
name: 'auth',
initialState: {
isAuthenticated: false,
},
reducers: {
setAuthenticated: (state) => {
state.isAuthenticated = true;
},
setUnauthenticated: (state) => {
state.isAuthenticated = false;
},
},
});
export const { setAuthenticated, setUnauthenticated } = authSlice.actions;
// Async action for validating token
export const validateToken = (token) => async (dispatch) => {
try {
// Make an API call to the backend with the token
const response = await fetch('/validate-token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token }),
});
// Check the response
if (response.ok) {
dispatch(setAuthenticated());
} else {
dispatch(setUnauthenticated());
}
} catch (error) {
// Handle error if needed
console.error('Error validating token:', error);
dispatch(setUnauthenticated());
}
};
export default authSlice.reducer;