React Navigation v5 Authentication Flows (Screens as Different Files)
Asked Answered
J

1

1

If we see in the doc example: https://reactnavigation.org/docs/auth-flow/ :

function SignInScreen() {
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');

  const { signIn } = React.useContext(AuthContext); // ????

  return (
    <View>
      <TextInput
        placeholder="Username"
        value={username}
        onChangeText={setUsername}
      />
      <TextInput
        placeholder="Password"
        value={password}
        onChangeText={setPassword}
        secureTextEntry
      />
      <Button title="Sign in" onPress={() => signIn({ username, password })} />
    </View>
  );
}

SignInScreen is located in the same App.js. If we put out SignInScreen as a new file SignInScreen.js, how to dispatch the signIn from SignInScreen.js?

Jacqui answered 13/6, 2020 at 13:34 Comment(0)
G
1

You must have a wrapper for SignInScreen

// App.js
import SignInScreen from '...'

// Export the context
export const AuthContext = React.createContext();

export default function App() {
  // ... some bootstrap code
  // https://reactnavigation.org/docs/auth-flow/#implement-the-logic-for-restoring-the-token
  const authContext = React.useMemo(
    () => ({
      signIn: async (data) => { ... },
    }),
    []
  );

  return (
    <AuthContext.Provider value={authContext}>
      <SignInScreen />
    </AuthContext.Provider>
  );
}
import { AuthContext } from "./App.js"

function SignInScreen() {
  // Must be child of AuthContext.Provider
  const { signIn } = React.useContext(AuthContext);

  return (
    <View>
      ...
    </View>
  );
}
Grane answered 13/6, 2020 at 13:56 Comment(10)
I mean SignInScreen is external file and imported in App.js. SignInScreen is already child of AuthContext.Provider, but I'm not sure how to access the same AuthContext in SignInScreen.js?Jacqui
I dont understand the problem, why is it matter if its an external file? Just import and render itGrane
You mean how to access the same AuthContext? Just export it, Ill add an exampleGrane
Yes, AuthContext is undefined. Tia.Jacqui
@JeafGilbert See example, export the context and import it in every component which is a child of the providerGrane
Btw additional question about this context, can we hook state in external child screen to a parent state? I want to rerender child's component if parent state changed.Jacqui
I managed to update parent's state from child using that Memo, but it doesn't rerender the child's component.Jacqui
If the consumer is a child of a provider so yes, better ask a new question with more detailsGrane
Okay, creating new question.Jacqui
Please have a look: #62387781Jacqui

© 2022 - 2024 — McMap. All rights reserved.