devYuraKim / react

udemy - jonas schmedtmann
0 stars 0 forks source link

Re11-worldwise > src > contexts > AuthContext | unable to use useNavigate() #23

Closed devYuraKim closed 2 months ago

devYuraKim commented 2 months ago

I decided to manage navigation within the AuthContext, rather than handling it inside the User component after logout. This would centralize the navigation logic, making it easier to reuse the same path consistently throughout the app.

User component

function User() {
  const { user, logout } = useAuth();
  const navigate = useNavigate();

  return (
    <div className={styles.user}>
      <img src={user.avatar} alt={user.name} />
      <span>Welcome, {user.name}</span>
      <button
        onClick={() => {
          logout();
          navigate("/"); //(1)delete this line of code in User component
        }}
      >
        Logout
      </button>
    </div>
  );
}

AuthContext component

  function logout() {
    dispatch({ type: "logout" });
    navigate("/"); //(2)and insert it here
  }

Then got this error

Error: useNavigate() may be used only in the context of a component.

devYuraKim commented 2 months ago

TL;DR: BrowserRouter is required for useNavigate

Solution was quite straightforward: move the AuthProvider inside the BrowserRouter

From this:

function App() {
  return (
    <> 
      <AuthProvider>
        <CitiesProvider>
          <BrowserRouter>
//... the rest of the code

To this:

function App() {
  return (
    <>
      <BrowserRouter>
        <AuthProvider>
          <CitiesProvider>
//... the rest of the code