Search code examples
reactjsreact-nativecomponentsexpostate

React Native, global useState?


I have a Fire class, and the uid return undefined if the user is not connected, string (his uid) if he is connected.

Sometime my render depend on this.

For example :

const [auth, setAuth] = useState<undefined|string>(Fire.shared.uid);

[...]

<Text>{(auth == undefined) ? "not authentificated" : "great")}</Text>

We can imagine the user is not connect so the text will be not authentificated. Now he will Sign in or Sign up in an other page, so the uid variable in Fire class will change. So how I'm suppose to change the state value?

There is no useState global or something like that?

Thanks.


Solution

  • you should use context:

    page-context.js

    export const PageContext= React.createContext();
    

    app.js

    const App = () => {
    const [auth, setAuth] = useState<undefined|string>(undefined);
    
    return(
        <PageContext.Provider value={[auth, setAuth]}>
           <NavigationContainer> // your routes
        </PageContext.Provider>)
    

    OtherScreen.js

    function OtherScreen() {
        const [auth] = useContext(PageContext);
        return (<Text>{(auth == undefined) ? "not authentificated" : "great")}</Text>)
    }
    

    Sign.js

     function Sign() {
        const [auth, setAuth] = useContext(PageContext);
        return (<Button onPress={()=>setAuth("myUid)} />)
     }