如何在另一个组件中完成登录后调用 Auth.currentAuthenticatedUser()?

huangapple go评论79阅读模式
英文:

How to call Auth.currentAuthenticatedUser() after login is made in another component?

问题

我有一个AppBar组件,我想要显示当前登录的用户。在同一页上,我有一个Profile组件,它触发登录表单。问题是它们不同步,显然AppBar内部的currentAuthenticatedUser在登录之前被调用,而不是在登录之后被调用,除非刷新页面:

function AppBar() {
  const [user, setUser] = useState();
  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then((u) => {
        setUser(u.username);
      });
  }, []);

  return <div>AppBar: {user}</div>;
}

function Profile(props: any) {
    return <Authenticator>
      {({ user, signOut }: any) => {
        return <>
          <div>Profile: { user.username }</div>
          <button onClick={() => signOut()}>Sign Out</button>
          </>;
      }}
    </Authenticator>
}

function App() {
  return <b><AppBar /><Profile /></b>;
}

如何在另一个组件中完成登录后调用 Auth.currentAuthenticatedUser()?

登录后:

如何在另一个组件中完成登录后调用 Auth.currentAuthenticatedUser()?

刷新页面后:

如何在另一个组件中完成登录后调用 Auth.currentAuthenticatedUser()?

如何在登录后立即在AppBar中显示用户名,而无需刷新页面?谢谢!

英文:

I have AppBar component which I want to show currently logged in user. On the same page I have Profile component, which triggers login form. The problem is that they are not synched, obviously currentAuthenticatedUser inside AppBar is called before login is made and not called after, unless page is refreshed:

function AppBar() {
  const [user, setUser] = useState();
  useEffect(() =&gt; {
    Auth.currentAuthenticatedUser()
      .then((u) =&gt; {
        setUser(u.username);
      });
  }, []);

  return &lt;div&gt;AppBar: {user}&lt;/div&gt;
}

function Profile(props: any) {
    return &lt;Authenticator&gt;
      {({ user, signOut }: any) =&gt; {
        return &lt;&gt;
          &lt;div&gt;Profile: { user.username }&lt;/div&gt;
          &lt;button onClick={() =&gt; signOut()}&gt;Sign Out&lt;/button&gt;
          &lt;/&gt;
      }}
    &lt;/Authenticator&gt;
}

function App() {
  return &lt;b&gt;&lt;AppBar /&gt;&lt;Profile /&gt;&lt;/b&gt;
}

如何在另一个组件中完成登录后调用 Auth.currentAuthenticatedUser()?

After login:

如何在另一个组件中完成登录后调用 Auth.currentAuthenticatedUser()?

After page refresh:

如何在另一个组件中完成登录后调用 Auth.currentAuthenticatedUser()?

How to display username in AppBar right after login without the need to refresh the page? Thanks!

答案1

得分: 1

  1. 本地状态:

AppBarProfile 组件的顶部设置你的 const [user, setUser] = useState(); 钩子。然后将 user 作为属性传递给 AppBar 组件,并将 setUser 传递给 Profile 组件,你需要在 Profile 内部创建一个组件,该组件将获取此属性,然后在 Authenticator 组件内渲染。

  1. 上下文:

这与上面的过程类似,但你需要使用 React.createContext(&lt;&lt;context_data_here&gt;&gt;) 语法。如果你的应用程序需要在许多组件上访问 user,我建议使用这种方法。如果不是这种情况,建议使用本地状态。

如果你不熟悉上下文,我建议观看这个 视频

英文:

You can achieve that functionality by either using local state or context

  1. Local state:

setup your const [user, setUser] = useState(); hook on top of AppBar and Profile components. Then pass down user as prop on the AppBar component and pass down setUser on the Profile component, you would need to create an internal component inside Profile that would take this prop and then be rendered inside the Authenticator component.

  1. Context:

It is a similar process as above but you need to use the React.createContext(&lt;&lt;context_data_here&gt;&gt;) syntax. I would suggest using this approach if your app need access to user on many components. If that is not the case using local state is recommended.

If you are not familiar with context I'd suggest watching this video

答案2

得分: 0

解决方案来自这里

function AppBar() {
  const [signedUser, setSignedUser] = useState<{ username: string }>();
  useEffect(() => {
    authListener();
  }, []);

  async function authListener() {
    Hub.listen("auth", (data) => {
      switch (data.payload.event) {
        case "signIn":
          return setSignedUser(data.payload.data);
        case "signOut":
          return setSignedUser(undefined);
      }
    });

    try {
      const user = await Auth.currentAuthenticatedUser();
      setSignedUser(user);
    } catch (err) {}
  }

  return <div>AppBar: {signedUser?.username}</div>;
}
英文:

Solution borrowed from here

function AppBar() {
  const [signedUser, setSignedUser] = useState&lt;{username: string}&gt;();
  useEffect(() =&gt; {
    authListener();
  }, []);

  async function authListener() {
    Hub.listen(&quot;auth&quot;, (data) =&gt; {
      switch (data.payload.event) {
        case &quot;signIn&quot;:
          return setSignedUser(data.payload.data);
        case &quot;signOut&quot;:
          return setSignedUser(undefined);
      }
    });

    try {
      const user = await Auth.currentAuthenticatedUser();
      setSignedUser(user);
    } catch (err) {}
  }

  return &lt;div&gt;AppBar: {signedUser?.username}&lt;/div&gt;
}

huangapple
  • 本文由 发表于 2023年1月9日 01:24:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定