I'm making an api call inside useEffect to fetch user data then trying to update the user state but the problem is, the user state stick to null even tho I successfully got the user from the axios call
here is my code :
AuthContext.js :
import { createContext , useState ,useEffect } from 'react'
import axios from 'axios'
export const AuthContext = createContext()
const AuthState = ({children}) => {
const [user , setUser] = useState(null)
useEffect(() => {
const fetchUser = async () => {
try {
const res = await axios.get('http://localhost:8000/auth/user' , { withCredentials : true })
console.log ('user in response => ' , res.data)
setUser(res.data)
console.log ('user in state => ' , user)
} catch(err) {
console.log('There was a problem')
}
}
fetchUser()
},[])
return (
<AuthContext.Provider value={user}>{children}</AuthContext.Provider>
)
}
export default AuthState
index.js :
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import AuthState from './AuthContext'
ReactDOM.render(
<React.StrictMode>
<AuthState>
<App />
</AuthState>
</React.StrictMode>,
document.getElementById('root')
);
console output (img) : console output
Why setUser does not update the user state?
CodePudding user response:
Here the user data is actually updating properly.
Having console.log('user in state => ' , user)
// is not proper way to test. This gives null because rerender did not happen in useEffect. To have a rerender affect useeffect you need to add user in dependency array [user].
but you dont need any change in code as this is working properly. For testing this I recommend add these in index.js.
ReactDOM.render(
<React.StrictMode>
<AuthState>
<AuthContext.Consumer> // <--To test
{(user) => <div>{user && user.id}</div>} // <--To test
</AuthContext.Consumer> // <--To test
<App />
</AuthState>
</React.StrictMode>,
document.getElementById('root')
);