Start learning free

LESSON 41 OF 58 · FULL-STACK: WHEN THINGS GO WRONG

Logged Out Halfway

Practice

A session doesn't last forever. If it ends while the visitor fills in the checkout form, the API answers POST /api/checkout with 401 and {"error": "Login required"}. Right now the page just shows "Login required" under the form, and the header still says the visitor is logged in.

A better answer is a round trip. Send the visitor to the login page with a next query parameter, and the given login page brings them back after a good login. A page for the orders, for example, would send them to /login?next=/orders.

Leaving a page throws its state away, so the form must be saved first. sessionStorage keeps strings for this browser tab, across pages and reloads:

sessionStorage.setItem("theme", "dark");
sessionStorage.getItem("theme");   // "dark"
sessionStorage.getItem("color");   // null: never saved

The check makes the API answer the first Pay with 401, logs in again and pays:

> the API will answer POST /api/checkout with 401
> click "Pay"
  request: POST /api/checkout {…} -> 401
      link: Log in -> /login (current)
      status: Please log in again to continue.
> the address bar
  /login?next=/checkout
> click "Log in" in "Log in"
  request: POST /api/login {…} -> 200
      text: Total: $41
      field "Name": "Ana Pop" (required)
      field "Address": "12 Garden Street, Cluj" (required)
> click "Pay"
  request: POST /api/checkout {…} -> 201

Your task: in client/src/pages/CheckoutPage.jsx, when the checkout throws an error with status 401: save name and address in sessionStorage, set the user to null, navigate to /login?next=/checkout and return. Then add an effect that runs once, when the page opens, and puts the saved values back ("" when nothing was saved).


Assignment
Follow the Coding Tutorial to handle a 401 at checkout: log the visitor out on the page, send them to log in and back, and keep what they typed.


Hint
Save the fields before navigate: once the page is gone, so are its values. getItem gives null for a missing key, and || "" turns that into an empty field. An effect with the dependency list [] runs only once.


STEP 1 OF 10
    Ctrl + Enter to check