I have got an issue where I need to update the name in my useContext and then straight away check it against another part of my code. Although when I check it against another part the name value in the context is still empty.
So this is my context file...
export const UserContext = createContext();
function UserContextProvider(props) {
const [user, setUser] = useState({
name: '',
email: ''
});
function updateUser(field, value) {
return new Promise((resolve, reject) => {
setUser((prevValue) => {
return {...prevValue, [field]: value}
})
resolve();
})
}
return (
<UserContext.Provider value={{user, updateUser}}>
{props.children}
</UserContext.Provider>
)
}
And this is what I want to run...
const { user, updateUser } = useContext(UserContext);
async function method(event) {
event.preventDefault();
await updateUser("name", "Shaun")
console.log(user);
}
I also tried with async and await but that didn't work either
I have re-produce the issue in my codesandbox here: https://codesandbox.io/s/youthful-smoke-fgwlr?file=/src/userContext.js