Using state set in context provider for fetch call in component

Viewed 30

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?

0 Answers
Related