简体   繁体   English

使用 Redux、React、NextAuth 在登录时调度操作客户端的最佳方式

[英]Best way to dispatch an action client-side upon Sign In using Redux, React, NextAuth

I am writing a web app based on the Spotify API.我正在编写一个基于 Spotify API 的 web 应用程序。 Once the user logs in using NextAuth, I want the app to automatically load the user's playlists.一旦用户使用 NextAuth 登录,我希望应用程序自动加载用户的播放列表。

I currently have it set up so that there is a button to load playlists and the button does not appear unless the user is logged in - this works and is simple.我目前已将其设置为有一个加载播放列表的按钮,并且除非用户登录,否则该按钮不会出现 - 这很有效并且很简单。 However, the button is unnecessary.但是,按钮是不必要的。 There is no use-case for the app that doesn't begin with loading the user's playlists.不以加载用户的播放列表开始的应用程序没有用例。

I currently have a thunk action written which was dispatched by the "Load Playlists" button to fetch the playlists asynchronously and add the playlists to the redux state.我目前编写了一个 thunk 操作,由“加载播放列表”按钮调度以异步获取播放列表并将播放列表添加到 redux state。

I can think of multiple possible options to get the automatic loading to work well, but I imagine there has to be a clean way.我可以想到多种可能的选项来使自动加载正常工作,但我想必须有一种干净的方式。 NextAuth has the [signIn event callback] https://next-auth.js.org/configuration/events#signin which seems like the right place to start. NextAuth 具有 [signIn 事件回调] https://next-auth.js.org/configuration/events#signin ,这似乎是正确的起点。 But since this would be run server-side, it would need some way to contact the client.但由于这将在服务器端运行,因此需要某种方式来联系客户端。

what I usually do is save the Jwt on local storage then use a use effect to get it if not existing then get it from the server using the thunk action.我通常做的是将 Jwt 保存在本地存储上,然后使用使用效果获取它,如果不存在,然后使用 thunk 操作从服务器获取它。 also, see How to wait for action to complete before redirecting in react redux?另请参阅如何在 React redux 中重定向之前等待操作完成? how to define the thunk如何定义thunk

Just observe the status in. a useEffect and once the status is authenticated call the load playlist action.只需观察 useEffect 中的状态,一旦状态通过身份验证,就调用加载播放列表操作。

import { useSession } from "next-auth/react"

export default function Component() {
  const { data: session, status } = useSession()
  
  useEffect(() => {
      if (status === "authenticated") {
           Load_Playlists()
      }
  }, [status])


  return <Main>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM