sveltejs / realworld

SvelteKit implementation of the RealWorld app
https://realworld.svelte.dev
MIT License
2.23k stars 353 forks source link

Why this project is using form actions for even logout feature? #151

Closed alokmahor closed 1 year ago

alokmahor commented 1 year ago

In the file ]realworld\src\routes\settings\+page.svelte

<form use:enhance method="POST" action="?/logout">
    <button class="btn btn-outline-danger">Or click here to logout.</button>
</form>

Its action is in file src\routes\settings\+page.server.js

logout: async ({ cookies, locals }) => {
    cookies.delete('jwt', { path: '/' });
    locals.user = null;
},

Why cant we do logout using on:click method call on logout button? What is benefit of using form actions for logout here?

dummdidumm commented 1 year ago

The benefit is that this also works without JavaScript, so in case the app's JS isn't loaded (which can happen more often than you might think, due to spotty internet connections etc). Furthermore, the alternative wouldn't really save you anything, as you would have to create a +server.js with a POST endpoint and do the stuff in there, with a manual redirect afterwards (which now happens automatically as a side-effect due to the load functiosn rerunning).

alokmahor commented 1 year ago

So do we need to always use <button> tag to logout using form actions?

I tried changing <button> to <div> but form action did not work.

<form use:enhance method="POST" action="?/logout">
    <div class="btn btn-outline-danger">Or click here to logout.</div>
</form>
dummdidumm commented 1 year ago

The button has special semantic meaning, for forms but also in general. You should always prefer a button over a div in such cases

benmccann commented 1 year ago

You can make it a button. If you have further questions, please ask them on Discord. We use GitHub only for bugs and not for support