본문 바로가기

개발하자

{#wait}을(를) 다시 실행하는 방법...} 스벨테에서?

반응형

{#wait}을(를) 다시 실행하는 방법...} 스벨테에서?

나는 이것이 완전히 클라이언트 사이드 렌더링이 되기를 원한다.. 그래서 약속을 다시 하기 위해 페이지를 새로 고치고 싶지는 않습니다..

여기 내가 만든 암호가 있다..

{#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}

나는 새로 고침 버튼이 약속만 다시 실행하고 의도한 대로 결과를 얻길 원한다.




약속을 API 요청에 하드코딩하는 대신 변수에 저장하고 변수를 새로 고치는 함수를 추가(즉, 쿼리를 다시 실행)하고 해당 함수를 버튼의 클릭 이벤트에 바인딩할 수 있습니다.

이런 거 말이야:

<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}



변경 시 재실행을 트리거하는 매개변수를 함수에 전달합니다.

{#await myFetchMethod("/api/v1/me", triggerParameter)}
...
{:then result}
...
{:catch error}
...
{/await}

매개 변수가 반드시 비동기 함수 내부에서 사용되어야 하는 것은 아니다. 그러나 파라미터의 값이 바뀌면 함수가 다시 실행된다. (입력이 변경되면 새로운 출력이 예상됩니다.).

새로 고침 버튼으로 트리거하려면 다음 작업을 수행할 수 있습니다:

<script>
  let trig = false;
</script>

{#await myFetchMethod("/api/v1/me", trig)}
    <Loading />
{:then loggedIn}
   ...
{:else}
   ...
{:catch error}

    <p>Can't connect to the server!</p>
    <button on:click={() => trig = !trig}>Refresh</button>
{/await}

반응형