Start learning free

LESSON 102 OF 161 · FRONTEND: REACT ROUTES AND SHARED STATE

Go There from Code

Practice

A Link changes the address when the visitor clicks it. Sometimes the page must move only after something happens in code, like after the server has answered. React Router's useNavigate gives you a function, navigate, that changes the address from code, without loading a new page. For example, after saving a review:

const navigate = useNavigate();

async function saveReview() {
  await sendReview(text);
  navigate("/products/3");
}

Each move adds an entry to the browser's history, so Back returns to the page before. After an order, that page is the checkout form, and Back would offer it again for a second order. navigate(to, { replace: true }) puts the new address in place of the current one, so Back skips the form.

The API can also refuse: POST /api/orders with an empty email answers 400 with {"error": "A valid email is required"} and no id. Then the page must show the error and stop, not go to /thanks/undefined.

The check sends the form empty, then with an email, then presses Back:

> click "Place order"   (Email empty)
  request: POST /api/orders {"email": ""} -> 400
  alert: A valid email is required
> type "eva@example.com" into "Email"
> click "Place order"
  request: POST /api/orders {"email": "eva@example.com"} -> 201
  heading 2: Thank you!
  text: Your order number is 1001.
> the address bar
  /thanks/1001
> press the browser's Back button
> the address bar
  /cart

Your task: in src/CheckoutPage.jsx, get navigate from useNavigate(). When the form is sent, wait for placeOrder(email). If the answer has an error, show it with setError and return; otherwise go to /thanks/ plus the order's id with replace: true.


Assignment
Follow the Coding Tutorial to send the visitor to the thanks page from code once the order is placed, with the form replaced in the history.


Hint
The if for order.error goes above the navigate line. Without the return inside it, the page still leaves for /thanks/undefined.


STEP 1 OF 6
    Ctrl + Enter to check