How to use history.push() with state parameter and also href to call the same route?

Asked

Viewed 17 times

0

My application has private screens on which the user can browse freely, but when trying to access some private area, the user is redirected to login screen. I would like the user to be redirected back to the screen he was previously on, proceeding normally. I have several pages in the same situation.

It would be more or less like in a virtual store, where we can browse and consult products, but when you click buy, it prompts you to login. When logging in we pick up where we were, on the same purchase screen.

I tried to use the history.push() past the pathname and in the status step the route of the page where I am to redirect back to it after login.

My code on the history.push screen is so:

  history.push({
    pathname: '/login',
    state: {
      path_retorno: '/agendamento',
    }
  });

On the login screen use useEffect() capture and store this route. After login, if there is path_return, redirect to it. Here is:

const [path_retorno, setPathRetorno] = useState("");
useEffect(() => {
    setPathRetorno(props.location.state.path_retorno);
  }  
}, []);  

So great, it works, but I also have the link that calls the same login screen, which is called by href:

<a href="/login"> Entrar </a>

Here is my problem, if I try to access directly by link get error:

TypeError: Cannot read property 'path_retorno' of undefined
(anonymous function)
  39 |  useEffect(() => {
> 40 |      setPathRetorno(props.location.state.path_retorno);
     | ^  41 |  }, []);  
  42 | 
  43 | 
View compiled
▶ 12 stack frames were collapsed.

As I’m accessing the link, I don’t even have the property "path_return".

How can I leave this functional for the two forms of access, both by history.push() how much for href? Or is there a better way to achieve that behavior?

I thank the community

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.