P
P
Pavel2021-01-14 01:19:06
React
Pavel, 2021-01-14 01:19:06

How to get rid of double data passing through useContext?

There is App.js in which I pass the state to the component through useContext. Further in the component in useEffect I use this state BUT!! comes undefined first, then the state changes to the desired one. The problem is that useEffect'e is requesting data to the server and the 2nd load is obtained.
app.js

<UserContext.Provider value={{ user, setUser }}>
        <Header />
      </UserContext.Provider>


Header.js

const { user, setUser } = useContext(UserContext)

  useEffect(() => {
    const token = user.token
    const getResouce = async () => {
      const getRes = await axios
        .get('/api/game/res', {
          headers: { 'x-auth-token': token },
        })
        .catch((error) => {
          console.log(error.response)
        })
    }
  }, [user])


It turns out that first user = undefined axios gives an error, then the user changes and re-renders normally. How to bypass it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question