Skip to content

Commit

Permalink
favoriting
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Nov 4, 2022
1 parent 4848548 commit 11ffd42
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 23 deletions.
41 changes: 19 additions & 22 deletions src/lib/ArticleList/ArticlePreview.svelte
Original file line number Diff line number Diff line change
@@ -1,23 +1,8 @@
<script>
import * as api from '$lib/api.js';
import { enhance } from '$app/forms';
export let article;
export let user;
async function toggle_favorite() {
// optimistic UI
if (article.favorited) {
article.favoritesCount -= 1;
article.favorited = false;
} else {
article.favoritesCount += 1;
article.favorited = true;
}
({ article } = await (article.favorited
? api.post(`articles/${article.slug}/favorite`, null, user && user.token)
: api.del(`articles/${article.slug}/favorite`, user && user.token)));
}
</script>

<div class="article-preview">
Expand All @@ -32,15 +17,27 @@
</div>

{#if user}
<div class="pull-xs-right">
<button
class="btn btn-sm {article.favorited ? 'btn-primary' : 'btn-outline-primary'}"
on:click={toggle_favorite}
>
<form
method="POST"
action="/article/{article.slug}?/toggleFavorite"
use:enhance={() => {
// optimistic update
if (article.favorited) {
article.favorited = false;
article.favoritesCount -= 1;
} else {
article.favorited = true;
article.favoritesCount += 1;
}
}}
class="pull-xs-right"
>
<input hidden type="checkbox" name="favorited" checked={article.favorited} />
<button class="btn btn-sm {article.favorited ? 'btn-primary' : 'btn-outline-primary'}">
<i class="ion-heart" />
{article.favoritesCount}
</button>
</div>
</form>
{/if}
</div>

Expand Down
17 changes: 16 additions & 1 deletion src/routes/article/[slug]/+page.server.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,23 @@ export const actions = {

deleteArticle: async ({ locals }) => {
if (!locals.user) throw error(401);
await api.del(`articles/${article.slug}`, locals.user.token);

await api.del(`articles/${article.slug}`, locals.user.token);
throw redirect(307, '/');
},

toggleFavorite: async ({ locals, params, request }) => {
if (!locals.user) throw error(401);

const data = await request.formData();
const favorited = data.get('favorited') !== 'on';

if (favorited) {
api.post(`articles/${params.slug}/favorite`, null, locals.user.token);
} else {
api.del(`articles/${params.slug}/favorite`, locals.user.token);
}

throw redirect(307, request.headers.get('referer') ?? `/article/${params.slug}`);
}
};

0 comments on commit 11ffd42

Please sign in to comment.