In React I'm using the context API to set the user data or the errors returned by the API request:
// context
const [currentUser, setCurrentUser] = useState("")
const [error, setError] = useState("")
async function login(credentials) {
setError("")
try {
...API request
const data = await response.json()
if(data.success) {
setCurrentUser(data)
} else {
setError(data.error)
}
} catch (error) {
setError("Something went wrong. Please try again.")
}
}
<AuthContext.Provider value={login, currentUser, error}>
{children}
</AuthContext.Provider>
Then in my component:
//component
const { login, currentUser, error } = useContext(AuthContext)
const onSubmit = async (credentials) => {
setLoading(true)
await login(credentials)
resetForm({})
setLoading(false)
!error && navigate("/")
}
return (
...
)
Now the onSubmit function allows the user to navigate to / even if there is an error set by the context - this is because (I think) the error is still null by the time it's checked and the component doesn't get the chance to rerender to get the newest value.
What would be the best approach to avoid this behavior? Should I handle the error locally in the component and not the context? If yes, what would be the best way on doing so in my scenario?