reach / router

Home Page:https://reach.tech/router

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] Why cant I pass state when I use navigate(-1)

sas604 opened this issue · comments

Hello,
Why when I use navigate and pass it -1, the state is not being applied.

This works

<button onClick={ ()=> navigate('/', {state:{id:12345})}>back</button>   
                   

But this does not

<button onClick={ ()=> navigate(-1, {state:{id:12345})}>back</button>   
                   

What am I doing wrong?
Than you.

which navigate are you using?

if you are using history.navigate, it is implemented this way

navigate(to, { state, replace = false } = {}) {
if (typeof to === "number") {
source.history.go(to);
} else {

which navigate are you using?

if you are using history.navigate, it is implemented this way

navigate(to, { state, replace = false } = {}) {
if (typeof to === "number") {
source.history.go(to);
} else {

So, the state is not being passed if there a number in the place of to? Is there another way to navigate to the previous page and pass the state?

you can add a wrapper around it.
maybe using something like this

const source = createMemorySource('/') // default route
// will be used in reach-router provider
const history = createHistory(source)
const { navigate } = history
const dangerouslyGoToLastRoute = async state => {
  try {
    source.history.go(-1)
    const lastRoute = source.history.entries[source.history.index].pathname
    source.history.entries.pop()
    if (lastRoute) await navigate(lastRoute, { replace: true, state })
  } catch (error) {
    console.log(error)
  }
}