Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redo {#await ...} in Svelte?

I want this to be fully client side rendering.. So, I don't want to refresh the page just to redo the promise..

Here's the code that I made..

{#await myFetchMethod("/api/v1/me")}
    <Loading />
{:then loggedIn}
    {#if loggedIn}
        <Link class="mb-0 h3" to="/profile">Profile</Link>
        <Link class="mb-0 h3" to="/logout">Logout</Link>
    {:else}
        <Link class="mb-0 h3" to="/login">Login</Link>
        <Link class="mb-0 h3" to="/register">Register</Link>
    {/if}
{:catch error}
    <p>Can't connect to the server!</p>
    <button on:click={whatShouldIDoHere}>Refresh</button>
{/await}

I want the refresh button to just redo the myFetchMethod("/api/v1/me") promise and get the result as intended.

like image 668
nafkhanzam Avatar asked Jul 17 '19 04:07

nafkhanzam


1 Answers

Instead of having the promise hardcoded to your API request, you could store it into a variable, add a function that refreshes the variable (i.e. fires the query again) and bind that function to the button's click event.

Something like this:

<script>
  let doLoginCheck = checkIfLoggedIn()

  function tryAgain() {
    doLoginCheck = checkIfLoggedIn()
  }

  function checkIfLoggedIn() {
    return fetch('/api/v1/me')
      .then(res => {
        if (!res.ok) {
          throw new Error('Cannot connect to server!');
        }
        return res.json();
      });
  }
</script>

{#await doLoginCheck}
  <Loading />
{:then loggedIn}
  {#if loggedIn}
    <Link class="mb-0 h3" to="/profile">Profile</Link>
    <Link class="mb-0 h3" to="/logout">Logout</Link>
  {:else}
    <Link class="mb-0 h3" to="/login">Login</Link>
    <Link class="mb-0 h3" to="/register">Register</Link>
  {/if}
{:catch error}
  <p>{error.message}</p>
  <button on:click={tryAgain}>Refresh</button>
{/await}
like image 171
Thomas Hennes Avatar answered Oct 17 '22 05:10

Thomas Hennes