Cristo
Cristo

Reputation: 710

svelte toast bootstrap fired only after second event

Event only fires sometimes, usually after second click of the same type.

So toast wont trigger more probably if do something like 1x add new, 1x update, 1x remove, etc...

But it will if same action several times like 5x add new, triggers after the second

...

// toast notify
import { Toast } from "bootstrap";

let toastEl;
let opc = { text: "", color: "" };

const mostrarMensaje = (text, color) => {
    opc = {
        text: text,
        color: color,
    };
    new Toast(toastEl).show();

};


...
        <!-- Toast notify -->
        <div class="toast-container position-absolute top-0 end-0 p-3">
            <div
                bind:this={toastEl}
                class="toast align-items-center text-dark bg-{opc.color}"
                role="alert"
                aria-live="assertive"
                aria-atomic="true"
            >

Sample code url : https://svelte.dev/repl/04e5e8a7511b44aca203adeb5817f204?version=3.48.0

Upvotes: 0

Views: 274

Answers (1)

Thomas Hennes
Thomas Hennes

Reputation: 9939

The problem lies with the way you set the background color in your toast:

class="toast align-items-center text-dark bg-{opc.color}"

Initially, when the component is first rendered (even though it is not shown), opc.color is an empty string, making the last class in your definition bg-, which is not valid.

If you initially set opc.color to "success", you will see the toast appear correctly when you add your first todo. However this is not a solution as the issue will persist for your other actions, delete and update.

The solution is to make use of Svelte's class: notation to add conditional classes to your toast div:

class="toast align-items-center text-dark"
class:bg-success={opc.color === "success"}
class:bg-danger={opc.color === "danger"}
class:bg-warning={opc.color === "warning"}

with this, the correct class will be appended depending on the current value of opc.color.

Working REPL

Side note: you will see in the linked REPL that I removed reactive declarations for your add, delete and update functions. These do not need to be reactive, and should be declared as normal functions/arrow functions.

Upvotes: 1

Related Questions