I've got a file called LoginPage.jsx
which calls a function in a utility file called AuthContext.jsx
, the utility file handles the request to the backend server to authenticate a user. If no user is found or any other error is returned, how do I send that back to the LoginPage.jsx
file to be handled and displayed to the user?
Asked
Active
Viewed 28 times
0

larkx
- 71
- 1
- 9
1 Answers
1
One possible way to pass error from context to component is to use a custom hook that wraps the useContext
function and throws an error if the context is undefined. This way, you can access the context value in any component that uses the hook, and handle the error accordingly. For example, you can create a useUserContext
hook like this:
const useUserContext = () => {
const context = useContext(UserContext);
if (context === undefined) {
throw new Error("useUserContext was used outside of its Provider");
}
return context;
};
Then, in your AuthContext.jsx
file, you can set the error state in the catch block of your fetch
request, and pass it along with the user
and signout
values to the UserContext.Provider
:
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const signout = () => setUser(null);
useEffect(() => {
const fetchUser = () => {
fetch("https://localhost:8000/api/")
.then((response) => response.json())
.then((result) => setUser(result.results))
.catch((error) => setError(error)); // set error state here
};
fetchUser();
}, []);
const contextValue = useMemo(
() => ({ user, signout, error }), // pass error value here
[user, signout, error]
);
return (
<UserContext.Provider value={contextValue}>{children}</UserContext.Provider>
);
};
Finally, in your LoginPage.jsx
file, you can use the useUserContext hook to access the error value and display it to the user if it exists:
const LoginPage = () => {
const { user, signout, error } = useUserContext(); // use custom hook here
return (
<div className="login-page">
{user ? (
<div>
<h1>Welcome, {user.name.first}</h1>
<button onClick={signout}>Sign out</button>
</div>
) : (
<div>
<h1>Please log in</h1>
{error && <p className="error-message">{error.message}</p>} // display
error message here
</div>
)}
</div>
);
};
To learn more, see

Pluto
- 4,177
- 1
- 3
- 25