Home > OS >  State is not passed or received in between components when send through <link to/>
State is not passed or received in between components when send through <link to/>

Time:01-20

I have one component, which displays different content in dependence of a state. The state is defined in the component and used in the first render, which works properly. After that each component which is rendered inside the component sets another state onclick, which is no problem, because i could just pass the function to the component.

function Modules(props) {
  const [state, setState] = useState(props.state);
  //use location to get the state from the previous page
  const location = useLocation();

  //rerender the page when the state changes
  React.useEffect(() => {
    setState(location.state);
    setState(props.state);
  }, [location.state, props.state]);

  const handleClick = (e) => {
    console.log(e);
    console.log(location);
    setState({ currentComponent: e });
  };

  const modules = [];

  const projects = [];

  return (
    <div>
      {state.currentComponent === "chooseMod" && (
        <ModuleList modules={modules} setState={handleClick} />
      )}
      {state.currentComponent === "chooseProj" && (
        <ProjectList projects={projects} setState={handleClick} />
      )}
      {state.currentComponent === "setupMod" && (
        <ModSetupModal setState={handleClick} />
      )}
    </div>
  );
}

export default Modules;

Now I have a navigation which should set back the state when its clicked. This isn't working like expected. The useEffect never gets triggered.

This is how the part of my navigation which should set back the state looks like:

<Link to={{ pathname: "/", state: { currentComponent: "chooseMod" },}}>

I tried several different ways to achieve this but I always get a state: null in the location object. I'm glad for any ideas and impressions, thanks!

CodePudding user response:

The state parameter in the location pathname excepts and object and hence you can pass as many values as you need by passing then as an object like

CodePudding user response:

I finally got it myself. I think I was sending the state the wrong way in the link to. After changing it to this, I'm receiving the state correctly:

<Link to="/" state={{ currentComponent: "chooseMod" }}>

Maybe anyone can explain, why my first version didn't work?

  • Related