Home > Back-end >  How to pass state in useNavigate to another component
How to pass state in useNavigate to another component

Time:08-27

The main code is this:

const navigate = useNavigate();
    const gotToNext = () => {
            let formDef = {
                formCategoryCd: formCatCode,
                formTypeCd: formTypeCode,
                headerTitle: HeaderTitle,
                footerTitle: FooterTitle,
                verticalSectionNumber: vSecNumber,
                horizSectionNumber: hSecNumber,
                formDefName: FormDefName,
                tabNumber: 6,
                formFont: 10,
                formFontSize: 5.2,
            }
            FormServices.AddFormDef(formDef).then((res) => {
                setformDefData(res.data)
                navigate({ pathname: "/vertical_section", state:{formdef_data: res.data}});
            })
        }

The other component where I want to receive this state:

const location = useLocation();
useEffect(() => {
    // setdefLockData(location.state.formdef_data)
    console.log("data",location.state)
  }, []);

but I get null state there. Please guide what am I doing wrong here.

CodePudding user response:

Instead of this:

navigate({ pathname: "/vertical_section", state:{formdef_data: res.data}});

Try this instead:

navigate("/vertical_section", { state: { formdef_data: res.data } });

The state object should be passed as the second argument to the navigate function.

  • Related