So, I'm learning about React Context and try to implement it by creating an auth state for my React Native app. I tried following this Ben Awad's repo. This is what I've got so far:
// AuthContext.tsxexport const AuthContext = createContext<{ user: null | string; login: () => void;}>({ user: null, login: () => {},});export const AuthProvider = ({ children }: Props) => { const [user, setUser] = useState<null | string>(null); const { user: contextUser } = useContext(AuthContext); return (<AuthContext.Provider value={{ user, login: () => { setUser("My Name"); console.log("Auth Provider pressed"); console.log("user (state) " + user); console.log("contextUser (context) " + contextUser); }, }}> {children}</AuthContext.Provider> );};// Navigation.tsxexport const Navigation = ({}: Props) => { const { user } = useContext(AuthContext); return (<AuthProvider> {user ? <HomeScreen /> : <Button />}</AuthProvider>// Button.tsxexport const Button = ({}: Props) => { const { login } = useContext(AuthContext); return (<View><Touchable onPress={login}><Text style={styles.container}>Submit</Text></Touchable></View> )
The AuthProvider has 2 values. user
which is obtained from the useState()
. And, login
which calls the setUser
to change the user
on the useState()
and thus should change the user
on the first Provider value.
The onPress on Button will call login()
from the AuthProvider. The login()
on the AuthProvider will trigger setUser
to change the user
on the useState()
value from null to "My Name". Until this part, it works as expected.
But, even though the button successfully changes the user
value on the useState()
. It doesn't change the user
(changed to contextUser
for "debugging" purpose) on the Context, no mater how many times I click the button, the contextUser
will always be null.
Tl;dr: user value on AuthProvider doesn't change after the button is pressed. But, user on useState changes.
So, what happened? What did I do wrong? Anyone has any idea how to fix this? I've stuck with this issue for the last few hours and googled more about this. My code is similar to theirs (I compared mine with other people's code that also uses context & auth), but somehow this code doesn't work.
Anyway, on Navigation, it should also automatically re-renders (to be HomeScreen) after the user value on Context is changed to non-null. I still haven't tested if it'll work (well, the user value never changes). Anyone could also review it to see if it could also run as expected?