webapp/src/context/profile.tsx

80 lines
2.1 KiB
TypeScript
Raw Normal View History

import type { ProfileInput } from '../graphql/types.gen'
2022-12-07 08:37:40 +00:00
import { createEffect, createMemo, createSignal } from 'solid-js'
2022-12-01 17:16:14 +00:00
import { createStore } from 'solid-js/store'
2022-12-01 17:16:14 +00:00
import { loadAuthor, useAuthorsStore } from '../stores/zine/authors'
import { apiClient } from '../utils/apiClient'
import { useSession } from './session'
2022-12-01 17:16:14 +00:00
const userpicUrl = (userpic: string) => {
if (userpic.includes('assets.discours.io')) {
return userpic.replace('100x', '500x500')
}
return userpic
}
2022-12-01 17:16:14 +00:00
const useProfileForm = () => {
const { session } = useSession()
const currentSlug = createMemo(() => session()?.user?.slug)
const { authorEntities } = useAuthorsStore({ authors: [] })
const currentAuthor = createMemo(() => authorEntities()[currentSlug()])
2022-12-07 08:53:41 +00:00
const [slugError, setSlugError] = createSignal<string>()
2022-12-07 08:37:40 +00:00
const submit = async (profile: ProfileInput) => {
2023-02-09 22:39:52 +00:00
const response = await apiClient.updateProfile(profile)
if (response.error) {
setSlugError(response.error)
return response.error
2022-12-07 08:37:40 +00:00
}
2023-02-09 22:39:52 +00:00
return response
2022-12-07 08:37:40 +00:00
}
2022-12-01 17:16:14 +00:00
const [form, setForm] = createStore<ProfileInput>({
name: '',
bio: '',
2022-12-09 06:09:21 +00:00
about: '',
2022-12-02 06:40:26 +00:00
slug: '',
2022-12-01 17:16:14 +00:00
userpic: '',
links: [],
2022-12-01 17:16:14 +00:00
})
createEffect(async () => {
if (!currentSlug()) return
try {
await loadAuthor({ slug: currentSlug() })
setForm({
2022-12-01 17:16:14 +00:00
name: currentAuthor()?.name,
2022-12-03 11:17:19 +00:00
slug: currentAuthor()?.slug,
2022-12-01 17:16:14 +00:00
bio: currentAuthor()?.bio,
2022-12-09 06:09:21 +00:00
about: currentAuthor()?.about,
userpic: userpicUrl(currentAuthor()?.userpic),
links: currentAuthor()?.links,
})
2022-12-01 17:16:14 +00:00
} 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 19:28:43 +00:00
)
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,
2022-12-01 17:16:14 +00:00
})
}
}
2022-12-07 08:53:41 +00:00
return { form, submit, updateFormField, slugError }
2022-12-01 17:16:14 +00:00
}
export { useProfileForm }