shorif2000
shorif2000

Reputation: 2654

How to pass updated values to my component

I am trying to implement a prevent double click and disable button and change text of button during click event.

    let btnText = "Initial";
    let btnDisabled = false;

const handlClick = () => {
    if (btnDisabled) return;
    console.log("handlClick")
    btnDisabled = true;
    btnText = "Pending...";
    somFunction();
    btnText = "Initial";
    btnDisabled = false;
  }

<Button
      {btnDisabled}
      text={btnText}
        btnClass="btn btn-primary"
        on:click={handlClick}
      />

The updated values don't seem to pass down to the component

here is my Button component

<script>
  import { createEventDispatcher } from "svelte";

  const dispatch = createEventDispatcher();

  function click() {
    dispatch("click");
  }

  export let text = "Pending";
  export let shrink = false;
  export let btnClass = "";
  export let btnDisabled = false;
</script>

<button 
  disabled={btnDisabled} on:click={click} class={btnClass}>{text}</button>

<style>
  .button {
    border: 2px solid var(--theme_modal_button_border);
    border-radius: 0.5rem;
    padding-left: 25px;
    padding-right: 25px;
    font-size: smaller;

    font-weight: 700;
    background: var(--theme_modal_button_bg);
    color: var(--theme_button_color);
    padding-top: 12px;
    padding-bottom: 12px;
  }

  .button:before,
  .button:after {
    content: "";
    display: block;
    box-sizing: border-box;
    position: absolute;
    background: var(--theme_modal_button_bg);
  }

  .button:hover,
  .button:active {
    background: var(--theme_modal_button_bg_light);
    border: 2px solid var(--theme_modal_button_border_light);
  }

  .button:hover:before,
  .button:hover:after {
    height: 2px;
    background: var(--theme_modal_button_bg_light);
  }

  .button:focus {
    border-color: none;
    box-shadow: none;
    text-decoration: none;
    outline: none;
  }

  .button:active {
    transform: scale(0.9);
  }

  .button:hover,
  .button:focus,
  .button:active {
    outline: none;
  }
</style>

Upvotes: 1

Views: 426

Answers (1)

brunnerh
brunnerh

Reputation: 184516

The problem is probably how you do not handle asynchrony:

    btnDisabled = true;
    btnText = "Pending...";
    somFunction();
    btnText = "Initial";
    btnDisabled = false;

someFunction() is probably not blocking1, so the state will immediately be reset in the following two lines. someFunction should return a Promise and then be awaited here.

  const handlClick = async () => { // mark async to await
    console.log("handlClick")
    btnDisabled = true;
    btnText = "Pending...";
    await somFunction();
    btnText = "Initial";
    btnDisabled = false;
  }

REPL example

1Even for blocking functions, of which there are not many, the execution flow needs to be broken, so the UI is given a chance to update: REPL

Upvotes: 1

Related Questions