I'm developing an android application with React-Native and i use Jotai to manage states.There's a problem with the Jotai state updates.
When i try to update the state, it always returns the previous state. For example, i'm initializing the state with a constant value and when i update this value to another one and right after the update if a console.log the last state, it returns the initial value. And when i try to update it again right after the last update attempt, it returns the first update value not the last. In other words it always sets the state with the previous update value somehow.
Here is my code below :
const [userState, setUserState] = useAtom(userStateAtom) const submitLogin = async (values: FormValues) => { let userStateBuffer: any = { ...userState } const response = await login(values.phoneNumber, '') .then((res) => { userStateBuffer = res }) .catch((err) => { console.log(err) }) setUserState(userStateBuffer) console.log(userState) if (userState.status) { console.log('You're here') navigation.dispatch( StackActions.replace('Main') ); } else { console.log(userState.message) } }
Jotai initialization:
export const userStateAtom = atom<UserState>({ data: '', message: '', status: false})
First attempt console.log :
LOG {"data": "", "message": "", "status": false} LOG
Second attempt console.log :
LOG {"data": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE2NTg3NDM4NDgsImV4cCI6MTY1ODc0NDQ0OCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdCIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3QifQ.Ezp-ppOcavHjfEIBTEOxr5ZcwewYJ4Po9j6-zGKl1Z0","message": null,"status": true} LOG You're here
Anyone knows why this is happening ?