webapp/src/context/profile.tsx

91 lines
2.4 KiB
TypeScript
Raw Normal View History

import type { ProfileInput } from '../graphql/types.gen'
import { createContext, createEffect, createMemo, JSX, useContext } 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
type ProfileFormContextType = {
form: ProfileInput
actions: {
setForm: (profile: ProfileInput) => void
submit: (profile: ProfileInput) => Promise<void>
updateFormField: (fieldName: string, value: string, remove?: boolean) => void
}
}
const ProfileFormContext = createContext<ProfileFormContextType>()
export function useProfileForm() {
return useContext(ProfileFormContext)
}
const userpicUrl = (userpic: string) => {
if (userpic.includes('assets.discours.io')) {
return userpic.replace('100x', '500x500')
}
return userpic
}
export const ProfileFormProvider = (props: { children: JSX.Element }) => {
2022-12-01 17:16:14 +00:00
const { session } = useSession()
const [form, setForm] = createStore<ProfileInput>({})
2022-12-01 17:16:14 +00:00
const currentSlug = createMemo(() => session()?.user?.slug)
2022-12-07 08:37:40 +00:00
const submit = async (profile: ProfileInput) => {
try {
await apiClient.updateProfile(profile)
} catch (error) {
console.error('[ProfileFormProvider]', error)
throw error
2022-12-07 08:37:40 +00:00
}
}
2022-12-01 17:16:14 +00:00
createEffect(async () => {
if (!currentSlug()) return
try {
const currentAuthor = await loadAuthor({ slug: currentSlug() })
setForm({
name: currentAuthor.name,
slug: currentAuthor.slug,
bio: currentAuthor.bio,
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
})
}
}
const value: ProfileFormContextType = {
form,
actions: {
submit,
updateFormField,
setForm,
},
}
2022-12-01 17:16:14 +00:00
return <ProfileFormContext.Provider value={value}>{props.children}</ProfileFormContext.Provider>
}