在上下文提供商中使用状态设置在组件中获取调用

发布于 2025-01-26 15:39:31 字数 1177 浏览 0 评论 0原文

我有一个上下文提供商,在其中进行了调用以获取当前的用户ID,然后将其设置为在其他组件中使用的状态。

export const CurrentUserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null)

  const fetchCurrentUser = async () => {
    let response = await fetch("http://127.0.0.1:5000/dj-rest-auth/user/", authRequestOptions('GET'))
    response = await response.json()
    setCurrentUser(response.pk)
  }

  return (
    <CurrentUserContext.Provider value={{ currentUser, fetchCurrentUser }}>
      {children}
    </CurrentUserContext.Provider>
  )
}

export const useCurrentUser = () => useContext(CurrentUserContext)

我的目标是,在页面加载时,请在组件中调用fetchcurrentuser,然后使用由此作为另一个API调用的一部分设置的当前使用者状态。我在下面尝试过的内容:

useEffect(() => {
    fetchCurrentUser()
}, [])

useEffect(() => {
    fetch(`http://127.0.0.1:5000/api/user-conversation-brief/${currentUser}`, requestOptions('GET'))
        .then(response => response.json())
        .then(data => {
            setSideBarMessages(data)
            setLoading(true)
        })
        .catch(error => console.log(error))
}, [currentUser])

但这在初始页面渲染上不起作用。我将如何按预期运行?

I have a context provider within which a fetch call is made to get the current user ID and then set it as state to use in my other components.

export const CurrentUserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null)

  const fetchCurrentUser = async () => {
    let response = await fetch("http://127.0.0.1:5000/dj-rest-auth/user/", authRequestOptions('GET'))
    response = await response.json()
    setCurrentUser(response.pk)
  }

  return (
    <CurrentUserContext.Provider value={{ currentUser, fetchCurrentUser }}>
      {children}
    </CurrentUserContext.Provider>
  )
}

export const useCurrentUser = () => useContext(CurrentUserContext)

My goal is to, on page load, call fetchCurrentUser in a component and then use the currentUser state that is set as a result of that as part of another API call. What I've tried below:

useEffect(() => {
    fetchCurrentUser()
}, [])

useEffect(() => {
    fetch(`http://127.0.0.1:5000/api/user-conversation-brief/${currentUser}`, requestOptions('GET'))
        .then(response => response.json())
        .then(data => {
            setSideBarMessages(data)
            setLoading(true)
        })
        .catch(error => console.log(error))
}, [currentUser])

But this doesn't work on the initial page render. How would I go making it work as intended?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文