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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With