I creating website with authorization. And I want to show different icons on home page, if user auth or not. But componnet render earsly then data user data changing.
For authorization I use react context.
export const UserProvider = ({children}) =>{
const [user, setUser] = useState(getObjectCookie('user') === undefined ? null : getObjectCookie('user'))
const signIn = async ({email, password}) =>{
return await fetch('http://localhost:5000/user/add', {
method: 'POST',
body: JSON.stringify({
email: email,
password: password
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(res => res.json())
.then(resultData => {
console.log(resultData.message);
const userData = resultData.createdUser
setObjectCookie('user', {id: userData._id, email: userData.email}, {expires: new Date(2030, 1)})
console.log('User\'s cookie set');
})
.catch(error => {
console.log(error.message)
return Promise.reject(error)
})
}
}
To check what of icon use, I check of user auth in render html
<div className="d-flex flex-pow btn-header">
<div className=" d-flex flex-column center-elements">
<a href="/profile">
{user !== null ?
<>
<img src={require("../assets/icons/icon-profile.png")} alt="Вход" className="log-in" />
<p>Вход</p>
</> :
<>
<img src={equire("../assets/icons/header-entry.png")} alt="Вход" className="log-in" />
<p>Вход</p>
</>
}
</a>
</div>
</div>
But when I register icon not changing. I log path of action and how you can see Header render before user data is change. And I don't know how to fix this.
Function on register button
const registerUser = async (e) =>{
e.preventDefault()
await signIn(formData)
.then(res => {
console.log('Its redirect');
navigate('/')
})
.catch(error => console.log('SignIN error'))
}
Auth function in ReactContext
const signIn = async ({email, password}) =>{
return await fetch('http://localhost:5000/user/add', {
method: 'POST',
body: JSON.stringify({
email: email,
password: password
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(res => res.json())
.then(resultData => {
console.log(resultData.message);
const userData = resultData.createdUser
setObjectCookie('user', {id: userData._id, email: userData.email}, {expires: new Date(2030, 1)})
console.log('User\'s cookie set');
})
.catch(error => {
console.log(error.message)
return Promise.reject(error)
})
}
I try to useState and useEffect.
const [profileIcon, setProfileIcon] = useState(user !== null ? '../assets/icons/icon-profile.png' : '../assets/icons/header-entry.png')
const [profileLabel, setProfileLabel] = useState(user !== null ? 'Профиль' : 'Вход')
console.log('Header render');
useEffect(() =>{
if (user !== null){
setProfileIcon('../assets/icons/icon-profile.png')
setProfileLabel('Профиль')
} else{
setProfileIcon('../assets/icons/header-entry.png')
setProfileLabel('Вход')
}
}, [user])
const undottedUL = {
"listStyleType": "none"
}