webapp/src/context/profile.tsx

82 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-11-28 13:18:25 +00:00
import type { ProfileInput } from '../graphql/schema/core.gen'
2023-12-03 10:22:42 +00:00
import { createEffect, createMemo, createSignal } from 'solid-js'
2022-12-01 17:16:14 +00:00
import { createStore } from 'solid-js/store'
2023-12-03 10:22:42 +00:00
import { apiClient as coreClient } from '../graphql/client/core'
2023-11-28 18:04:51 +00:00
import { loadAuthor } from '../stores/zine/authors'
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 = () => {
2023-11-28 18:04:51 +00:00
const { author: currentAuthor } = useSession()
2022-12-07 08:53:41 +00:00
const [slugError, setSlugError] = createSignal<string>()
2022-12-07 08:37:40 +00:00
2023-12-03 10:22:42 +00:00
const apiClient = createMemo(() => {
if (!coreClient.private) coreClient.connect()
return coreClient
})
2022-12-07 08:37:40 +00:00
const submit = async (profile: ProfileInput) => {
2023-12-03 10:22:42 +00:00
const response = await apiClient().updateProfile(profile)
2023-02-09 22:39:52 +00:00
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: '',
2023-11-28 13:18:25 +00:00
pic: '',
links: [],
2022-12-01 17:16:14 +00:00
})
createEffect(async () => {
2023-11-28 13:18:25 +00:00
if (!currentAuthor()) return
2022-12-01 17:16:14 +00:00
try {
2023-11-28 13:18:25 +00:00
await loadAuthor({ slug: currentAuthor().slug })
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,
2023-11-28 13:18:25 +00:00
pic: userpicUrl(currentAuthor()?.pic),
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 }