webapp/src/context/profile.tsx

68 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-12-01 17:16:14 +00:00
import { createEffect, createMemo } from 'solid-js'
import { createStore } from 'solid-js/store'
import { useSession } from './session'
import { loadAuthor, useAuthorsStore } from '../stores/zine/authors'
import { apiClient } from '../utils/apiClient'
import type { ProfileInput } from '../graphql/types.gen'
const submit = async (profile: ProfileInput) => {
try {
await apiClient.updateProfile(profile)
} catch (error) {
console.error(error)
}
}
const useProfileForm = () => {
const { session } = useSession()
const currentSlug = createMemo(() => session()?.user?.slug)
const { authorEntities } = useAuthorsStore({ authors: [] })
const currentAuthor = createMemo(() => authorEntities()[currentSlug()])
const [form, setForm] = createStore<ProfileInput>({
name: '',
bio: '',
2022-12-02 06:40:26 +00:00
about: '',
slug: '',
2022-12-01 17:16:14 +00:00
userpic: '',
links: []
})
createEffect(async () => {
if (!currentSlug()) return
try {
await loadAuthor({ slug: currentSlug() })
setForm({
name: currentAuthor()?.name,
bio: currentAuthor()?.bio,
2022-12-02 06:40:26 +00:00
about: currentAuthor()?.about,
2022-12-01 17:16:14 +00:00
userpic: currentAuthor()?.userpic,
links: currentAuthor()?.links
})
} catch (error) {
console.error(error)
}
})
const updateFormField = (fieldName: string, value: string, remove?: boolean) => {
if (fieldName === 'links') {
if (remove) {
2022-12-01 19:28:43 +00:00
setForm(
'links',
form.links.filter((item) => item !== value)
)
2022-12-01 17:16:14 +00:00
} else {
2022-12-01 18:52:44 +00:00
setForm((prev) => ({ ...prev, links: [...prev.links, value] }))
2022-12-01 17:16:14 +00:00
}
} else {
setForm({
[fieldName]: value
})
}
}
return { form, submit, updateFormField }
}
export { useProfileForm }