Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I export text to/access text from another file in React Native?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
        ...
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading