In an AuthProvider.js, I have the following code written to catch and log errors in the console.
export const AuthProvider = ({children}) => {
const [user, setUser] = useState(null);
const [errorText, setErrorText] = useState('')
return (
<AuthContext.Provider
value={{
user,
setUser,
login: async (email, password) => {
try {
await auth().signInWithEmailAndPassword(email, password)
} catch(e) {
setErrorText(e);
console.log(e)
}
},
}}
>
{children}
</AuthContext.Provider>
)
}
I want to export these errors as text (strings) to another file (LoginScreen.js) so that the error can be displayed there in a Text component, as follows:
<Text style={styles.errorMsg}>{errorText}</Text>
As you can see, I’m already using a hook to set the error text to the correct value, but I’m not sure how to export this hook into another file, or if there’s a better method of exporting a string.
>Solution :
You can also pass the errorText to the value object of the Auth.Provider
Since, you’d be wrapping most of your App with Auth.Provider you can get access to these values, including errorText anywhere in the nested screens.
Inside LoginScreen.js
const LoginScreen = () => {
const auth = useContext(AuthContext);
const {errorText} = auth;
return (
...
<Text style={styles.errorMsg}>{errorText}</Text>
...
)
}