简体   繁体   English

如何在 Next.JS + Rails API 后端存储用户信息?

[英]How can I store user information in Next.JS + Rails API backend?

I'm new to Next.js and React in general, I used to develop the whole application with Rails.我是 Next.js 和 React 的新手,我曾经用 Rails 开发整个应用程序。

I want to combine rails API with Next.js.我想将 rails API 与 Next.js 结合起来。 My JWT backend has an endpoint that returns a JSON object containing user information when requested with JWT token in header.我的 JWT 后端有一个端点,当在标头中使用 JWT 令牌请求时,该端点返回包含用户信息的 JSON 对象。 In my _app.js , I'm trying to authenticate users using this backend by using useState and useEffect like this:在我的_app.js ,我试图通过使用useStateuseEffect来验证使用useState useEffect如下所示:

export default function MyApp(props) {
  const [user, setUser] = useState({})

  useEffect(function () {
    const token = localStorage.getItem('token')
    if (token) {
      fetch('http://localhost:3001/auto_login', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
        .then((resp) => resp.json())
        .then((data) => {
          console.log(data) // {id: 1, email: "test@example.com"}
          setUser(data)
          console.log(user) // {}
        })
    }
  }, [])

  return (
    <>
      { // some code }
    </>
  )
}

In my first console.log , it returns an object that I would like to store in user .在我的第一个console.log ,它返回一个我想存储在user However, in my second console.log where I expect to return the same result, I get an empty object instead.但是,在我希望返回相同结果的第二个console.log中,我得到了一个空对象。

Am I missing anything, or are there any points that I have to take into consideration as a whole?我是否遗漏了任何东西,或者有什么我必须整体考虑的要点? I've already tried implementing this with async/await , but that didn't seem to solve my problem.我已经尝试使用async/await实现它,但这似乎并没有解决我的问题。

It's because that effect isn't aware of the dependent objects state change.这是因为该效果不知道依赖对象的状态变化。

If you did this (see code below) you'd see user being logged.如果你这样做(见下面的代码),你会看到user被登录。 Eg within the context of the 1st effect's 1st run, even though you're setting the user state, inside the effect it's not aware of the new value.例如,在第一个效果的第一次运行的上下文中,即使您正在设置user状态,在效果内部它也不知道新值。

The sequence is like this.顺序是这样的。

  1. Component loads组件负载
  2. Effect runs with initial state of [] (this effectively means run once, and uses the current state, user => {} ) Effect 以[]初始状态运行(这实际上意味着运行一次,并使用当前状态, user => {}
  3. state [] => console.log(data)状态[] => console.log(data)
  4. state [] => setUser(data)状态[] => setUser(data)
  5. state [] => console.log(user) // currently {} state [] => console.log(user) // 当前{}
  6. effect is done.效果完成。

Look at the useEffect explanation here这里的useEffect解释

export default function MyApp(props) {
 const [user, setUser] = useState({ email: null, id: null })

 // same useEffect / modify your existing code 
 // you could add user in here .but then the api call will fire again, 
 // thus an infinite loop could happen, so you would need to wrap 
 // the call in an if to check to prevent that, see my alterations
 useEffect(function () {
    const token = localStorage.getItem('token')
    if (token && !user.id) {
      fetch('http://localhost:3001/auto_login', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      })
        .then((resp) => resp.json())
        .then((data) => {
          console.log(data) // {id: 1, email: "test@example.com"}
          setUser(data)
          console.log(user);
        })
    }
  }, [user]); // [] => changed to => [user]


 // new / additional useEffect 
 // alternatively this effect will trigger when 
 // this objects state changes (and you wont need the checks as per above)
  useEffect(() => {
    console.log(user);
  }, [user]);  

  return (
    <>
      { // some code, e.g if you referenced user here, example. user.email, it would work. }
      { // Would probably initially be empty, when when the ajax call completes the value would/could be set }
    </>
  )
}

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

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