I'm trying to assign "email" (which is a state) to "refEmail.current.value".
So I do setEmail(response.data)
and when I do a console.log(response.data)
, I have the expected data, but if I do immediately after a console.log(email)
, I still have the default value of my state. I tried using prevState but it doesn't change anything: setEmail(prevState => prevState, response.data)
This is my code:
const EditProfilModal = () => {
const [email, setEmail] = useState('exemple')
const refFirstname = useRef();
const refLastname = useRef();
const refEmail = useRef();
useEffect(() => {
const toFetchEmail = async () => {
try {
const params = JSON.parse(localStorage.getItem("user")).user_id;
const response = await axios.get(`http://localhost:4200/api/user/${params}`);
setEmail(prevState => prevState, response.data)
console.log(response.data)
console.log(email);
} catch (err) {
throw err;
}
};
toFetchEmail()
refFirstname.current.value = JSON.parse(localStorage.getItem("user")).user_firstname;
refLastname.current.value = JSON.parse(localStorage.getItem("user")).user_lastname;
refEmail.current.value = email;
}, []);
return (.....)
So, the first console.log return the expected data, but the second return the default value (example) instead of the expected data. Why, and how to update the state immediately?