Switch to API route for newsletter form submission 🫠
not using the latest SvelteKit use:enhance thingy but… hey!
This commit is contained in:
@@ -3,8 +3,6 @@
|
||||
</style>
|
||||
|
||||
<script lang="ts">
|
||||
import { enhance } from '$app/forms'
|
||||
import { dev } from '$app/environment'
|
||||
import { fly } from 'svelte/transition'
|
||||
import { quartOut } from 'svelte/easing'
|
||||
import { sendEvent } from '$utils/analytics'
|
||||
@@ -15,27 +13,41 @@
|
||||
export let past: boolean = false
|
||||
|
||||
let inputInFocus = false
|
||||
let formStatus: { error: string, success: boolean, message: string } = null
|
||||
let formStatus: FormStatus = null
|
||||
let formMessageTimeout: ReturnType<typeof setTimeout> | number
|
||||
|
||||
interface FormStatus {
|
||||
error?: string
|
||||
success?: boolean
|
||||
message: string
|
||||
}
|
||||
const formMessages = {
|
||||
PENDING: `Almost there! Please confirm your email address through the email you'll receive soon.`,
|
||||
MEMBER_EXISTS_WITH_EMAIL_ADDRESS: `This email address is already subscribed to the newsletter.`,
|
||||
INVALID_EMAIL: `Woops. This email doesn't seem to be valid.`,
|
||||
}
|
||||
|
||||
$: isSuccess = formStatus && formStatus.success
|
||||
|
||||
// Toggle input focus
|
||||
const toggleFocus = () => inputInFocus = !inputInFocus
|
||||
|
||||
// Handle form submission
|
||||
const handleForm = () => {
|
||||
return async ({ result, update }) => {
|
||||
formStatus = result.data
|
||||
async function handleForm (event: SubmitEvent) {
|
||||
const data = new FormData(this)
|
||||
const email = data.get('email')
|
||||
|
||||
console.log(result)
|
||||
// if (dev) {
|
||||
// }
|
||||
if (email) {
|
||||
const req = await fetch(this.action, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email })
|
||||
})
|
||||
const result: FormStatus = await req.json()
|
||||
formStatus = result
|
||||
|
||||
// If successful
|
||||
if (result.data.success) {
|
||||
if (formStatus.success) {
|
||||
sendEvent('newsletterSubscribe')
|
||||
update()
|
||||
} else {
|
||||
// Hide message for errors
|
||||
clearTimeout(formMessageTimeout)
|
||||
@@ -47,8 +59,7 @@
|
||||
|
||||
<div class="newsletter-form">
|
||||
{#if !isSuccess}
|
||||
<form method="POST" action="?/subscribe"
|
||||
use:enhance={handleForm}
|
||||
<form method="POST" action="/api/newsletter" on:submit|preventDefault={handleForm}
|
||||
out:fly|local={{ y: -8, easing: quartOut, duration: 600 }}
|
||||
>
|
||||
<div class="newsletter-form__email" class:is-focused={inputInFocus}>
|
||||
@@ -87,7 +98,7 @@
|
||||
in:fly|local={{ y: 8, easing: quartOut, duration: 600, delay: isSuccess ? 600 : 0 }}
|
||||
out:fly|local={{ y: 8, easing: quartOut, duration: 600 }}
|
||||
>
|
||||
<p class="text-xsmall">{formStatus.message}</p>
|
||||
<p class="text-xsmall">{formMessages[formStatus.message]}</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
Reference in New Issue
Block a user