Next.js Discord

Discord Forum

How to pass setState func from 1 page to another

Answered
Virginia's Warbler posted this in #help-forum
Open in Discord
Virginia's WarblerOP
Currently I can only think of passing it via params. Im not sure if that would even work.
Is there a better way of achieving that?
Answered by joulev
oh i thought you were running the setState inside one page and expect the state in another page.

you cannot send a function to another page because the function is not serialisable.

you need to lift the state to a layout that contains both of the pages, then run the function instead of sending it to another page.
View full answer

4 Replies

@Virginia's Warbler Currently I can only think of passing it via params. Im not sure if that would even work. Is there a better way of achieving that?
you have to lift the state to a layout that covers both pages

or yes search params is good too.

it depends on what exactly you are trying to send to the other page.
Virginia's WarblerOP
Ok. Currently I am trying to do it using search params.
                router.navigate({
                  pathname: '/mugshot/',
                  params: {
                    data: JSON.stringify({
                      mugshotPath: mugshotPath, 
                      setMugshotPath: setMugshotPath,
                    }),
                  },
                });


However, the setState function is not even coming out on the receiving page.
  const params = useLocalSearchParams();
  console.log({params});


{"params": {"data": "{\"mugshotPath\":\"\"}"}}

Why is that?
@Virginia's Warbler Ok. Currently I am trying to do it using search params. router.navigate({ pathname: '/mugshot/', params: { data: JSON.stringify({ mugshotPath: mugshotPath, setMugshotPath: setMugshotPath, }), }, }); However, the setState function is not even coming out on the receiving page. const params = useLocalSearchParams(); console.log({params}); `{"params": {"data": "{\"mugshotPath\":\"\"}"}}` Why is that?
oh i thought you were running the setState inside one page and expect the state in another page.

you cannot send a function to another page because the function is not serialisable.

you need to lift the state to a layout that contains both of the pages, then run the function instead of sending it to another page.
Answer
Virginia's WarblerOP
Ok, thank you