naf*_*zam 5 javascript node.js 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}
Run Code Online (Sandbox Code Playgroud)
我希望刷新按钮只是重做myFetchMethod("/api/v1/me")
承诺并按预期获得结果。
您可以将承诺存储到一个变量中,而不是将承诺硬编码到您的 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}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
598 次 |
最近记录: |