如何在 Svelte 中重做 {#await ...}?
How to redo {#await ...} in Svelte?
我希望这是完全客户端呈现。所以,我不想为了重做承诺而刷新页面。
这是我编写的代码..
{#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}
我希望刷新按钮仅重做 myFetchMethod("/api/v1/me")
承诺并获得预期结果。
您可以将 promise 硬编码到您的 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")}
<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}
我希望刷新按钮仅重做 myFetchMethod("/api/v1/me")
承诺并获得预期结果。
您可以将 promise 硬编码到您的 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}