Home > Net >  Context not updating value when change routes
Context not updating value when change routes

Time:07-13

So I have my context set like this:

import { createContext, ReactNode, useState } from "react";

type props = {
  children: ReactNode;
};

type GlobalContextType = {
  name: string;
  setName: (value: string) => void;
};

export const GlobalContext = createContext<GlobalContextType>(
  {} as GlobalContextType
);

export const GlobalProvider = ({ children }: props) => {
  const [name, setName] = useState<string>("");

  return (
    <GlobalContext.Provider value={{ name, setName }}>
      {children}
    </GlobalContext.Provider>
  );
};

And I also have a input

const { name, setName } = useContext(GlobalContext);

  const handleChange = (e: React.FormEvent<HTMLInputElement>): void => {
    setName(e.currentTarget.value);
  };

  <input
      placeholder="Insert a username"
      onChange={handleChange}
      data-testid="Login-input"
  />

If I log the "name" value that is changed through the setName it seems to work just fine But I also have a login button that redirects to another route /home.

export const Home = () => {
  const { name } = useContext(GlobalContext);
  return (
    <div>
      <p>{name} </p>
    </div>
  );
};

Here, the name displays as the default value that was set up in the context, not the updated one that I changed in the input. I tried to rewrite it but it doesn't seem to be wrong. Am I missing something?

CodePudding user response:

Does the page reload during the redirection? If yes, the state of name should be reverted back to the default value. Apparently data cannot be persisted this way.

You can refer to this post for more details: React Context API - persist data on page refresh

  • Related