Start learning free

LESSON 82 OF 161 · FRONTEND: REACT EFFECTS AND DATA

Loading in JavaScript

Practice

Your shop asks the API for its products when the page opens. The answer takes a moment. While it travels, products is still the empty list, so the page says 0 products. That is not true: the shop has products, they just have not arrived yet. The page needs to know that it is still loading.

In the starting code, the ProductList line has been taken out of App, so your page shows no products at all for now, not even 0 products. The ternary you write puts it back.

A loading state is a state variable that starts as true and turns false once the answer is in. The JSX then draws one thing or the other with a ternary, condition ? (…) : (…), inside curly braces. For example, a save button in another app could be drawn like this:

{saving ? (
  <p>Saving…</p>
) : (
  <button>Save</button>
)}

When saving is true, the first side is drawn; when it is false, the second. Each time a setter changes the state, React draws the component again and the ternary picks again. If nothing ever sets the state back to false, the message stays forever.

When the check opens your page, it must print:

> open the page
  request: GET /api/products ...
  screen while waiting:
      text: Cart (0)
      text: Loading products…
  answer: GET /api/products -> 200
  screen changes:
    -   text: Loading products…
    +   section "Products"
    +     text: 8 products
    +     … Mug $12, Notebook $7, … Gift card $50

Your task: in src/App.jsx, add a loading state that starts as true. Under the Cart (…) paragraph, show Loading products… while it is true and the ProductList when it is false. Then, in loadProducts, set loading to false once the products are in state.


Assignment
Follow the Coding Tutorial to add the loading state, the ternary that draws the message or the product list, and the line that ends the loading.


Hint
A ternary needs both of its sides: until you have written ) : ( and the ProductList, the editor shows a syntax error. setLoading(false) goes right after setProducts(data).


STEP 1 OF 6
    Ctrl + Enter to check

    Effect Loading in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free