Start learning free

LESSON 158 OF 161 · FRONTEND: INTERVIEW QUESTIONS

Toast Messages in JavaScript

Practice

A toast is a short message that pops up, like "Saved", and leaves on its own after a few seconds. In an interview, the tricky parts are that several toasts can be on the screen at once, and each one leaves on its own time.

Each toast needs an id, a number that names it and no other, so its timer and its Close button remove exactly that toast. setTimeout runs a function once, after a number of milliseconds, and the arrow function remembers the values it was made with:

const order = 42;
setTimeout(() => console.log("Order " + order + " is ready"), 3000);
// 3 seconds later: Order 42 is ready

A timer fires later than the code that started it. So when it changes state, use an updater function: it gets the list as it is when the timer fires, not the list from when the timer started.

The check clicks Save, waits 1000 ms, clicks Save twice, closes Saved #2, then lets time pass. Part of what it must see:

> click "Save"
    +     item: Saved #1
    +       button: Close
> 1000 ms pass
  screen: no change
> click "Save"
    +     item: Saved #2
> click "Save"
    +     item: Saved #3
> click "Close" in "Saved #2"
    -     item: Saved #2
> 2000 ms pass
    -     item: Saved #1
> 1000 ms pass
    -     item: Saved #3
    +   list "Messages" (empty)

Your task: in src/App.jsx, the Save button, the list and a counter ref, nextId, are already there. In save, give the toast the next id and add it to toasts, write removeToast, start a 3000 ms timer per toast, and add a Close button to each toast.


Assignment
Follow the Coding Tutorial to show a "Saved" toast for each click on Save, each leaving after 3 seconds or when its Close button is clicked.


Hint
Read nextId.current before you add 1 to it. Remove a toast with filter, keeping every id but the one to remove.


STEP 1 OF 7
    Ctrl + Enter to check

    Fe Toasts 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