next.js 如何在状态中维护用户数据,而无需在每个请求中都预取用户

bjp0bcyl  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(139)

我正在使用NextjsStrapi CMSRedux创建一个Web应用程序,并使用Cookie。但我必须检查每次请求时token是否未过期,如果已过期,我将isAuthenticated设置为false。

useEffect(() => {
        
        if (isAuthenticated) {
               dispatch(fetchUserDetails()); 
        }
    }, [isAuthenticated]);

但是isAuthenticated只针对登录和注销,我想知道的是,如何在token过期时将用户从状态中删除,是否应该设置一个从用户登录时注销用户的日期。
如果是这样,如何安排一个日期注销用户时,令牌到期与nexjs和strapi cms或建议检查令牌是否仍然是活跃的?

cotxawn7

cotxawn71#

不确定如果令牌过期,你是否真的需要手动注销用户,因为如果你试图用不正确的令牌访问受保护的strapi路由,你会收到403,所以基本上你可以从任何操作中注销,只要知道它收到403。
关于在“日期”上分派动作,我不会在这里使用日期这个词,因为问题是服务器有它自己的时钟时区等等,客户端也有自己的时钟和timzeone。处理这个问题的一般规则是避免所有的成本...
所以关于quetstion的redux部分,我已经有一年没有做过任何reducer/action creators了,在现代redux toolkit中,伪代码看起来像这样(注意计时器代码更多的是一个概念,只是在我的脑海中写出来的):

let timer;
const delay = 5000; 

const setTimer = (fn: () => void) => {
   if (typeof timer !== 'undefined') {
      return timer;
   }
   timer = setTimeout(() => fn(), delay);
   return timer;   
}

const clearTimer = () => {
   if (typeof timer !== 'undefined') {
      return clearTimeout(timer);
   }
}

export const timerMiddleware: Middleware = (store) => {
    return (next) => (action) => {
        if (action.type === someSortOfLoginActionType) {
             setTimer(() => store.dispatch(logoutAction());
        }
        if (action.type === someSortOfLogoutActionType) {
             clearTimer();
        }
        // prolly you needs some sort of reset timer
        // but i guess the proper place to handle is 
        // in setTimer function, so it resets if timer
        // already set

        return next(action);
    }
}

和一个createStore部件:

export const store = configureStore({
    reducer: { ... }
    middleware: (getDefaultMiddleware) => getDefaultMiddleware(..).concat(timerMiddleware)
})

不确定它是否适用于你的情况,但是这是我可以从描述中得出的结论。
希望有帮助!

相关问题