mike
mike

Reputation: 129

Redirect with useNavigate and state seems to be hard to accomplish

What I am trying to do: I have a form that a client is filling out. They choose the day and time of an appointment before paying for the appointment. During payment, they get redirected to a hosted payment page and then they come back to complete the process. When its redirected, some CC info is in the path. I am trying to useParams to get that info and then redirect to the page they were on. Part of the params tells me that their payment was approved and its all I need. I need to set state to approved based on this. Then use that state in my appointment page, finish the form and submit, setting the state back to false when done.

Current code:

const location = useLocation();
  let navigate = useNavigate();
const params = new URLSearchParams(location.search);
 <Route
                path='/confirm'
                element={
                  params.has('ssl_approval_code') ? (
                  
                    navigate('./appointments', { approved: true })
                  ) : (
                    <div style={{ height: '1000px' }}>
                      Error occurred while processing card. Please use a
                      different card or contact client.
                    </div>
                  )
                }
    />
  <Route
                exact
                path='/appointments'
                element={
                  <Appointment                 
                    navigate={navigate}      
                  />
                }
    />

Then trying to just do this at the end of my submit function navigate({ approved: false });

Currently my navigate isnt working at all. Before I had version 5 of react-router-dom using Redirect, but the state was messing up. But at that time it was atleast redirecting. It just wouldnt reset state so I switched to version 6 with useNavigate.

Upvotes: 2

Views: 4840

Answers (1)

Drew Reese
Drew Reese

Reputation: 202618

In react-router-dom v6 the state is sent in the options object in the second argument to navigate.

useNavigate

declare function useNavigate(): NavigateFunction;

interface NavigateFunction {
  (
    to: To,
    options?: { replace?: boolean; state?: any }
  ): void;
  (delta: number): void;
}

Move the object into the state property of the options object.

navigate('./appointments', { state: { approved: false } });

Upvotes: 3

Related Questions