wishlist-client/pages/home/index.tsx
kjuulh 28069a92f1
Some checks failed
continuous-integration/drone/push Build is failing
Created logic for creating lists
2022-04-25 22:32:24 +02:00

93 lines
2.4 KiB
TypeScript

import { NextPage } from 'next'
import HomeLayout from '../../components/layout/home/HomeLayout'
import CreateWish, {
BasePrompt,
} from '../../components/domain/wishes/createWish/CreateWish'
import { useEffect, useMemo, useState } from 'react'
import { createWish, Wish } from '../../components/domain/wishes/models'
import { v4 } from 'uuid'
import { result } from '../../components/common/result'
interface WishItem {
value: Wish
dirty: boolean
focus: boolean
}
const HomePage: NextPage = (props) => {
const stableId = useMemo(() => v4(), [])
const [wishes, setWishes] = useState<{ [key: string]: WishItem }>({
[stableId]: {
value: result.getValue(createWish(stableId, '')),
dirty: false,
focus: false,
},
})
const wishArr = useMemo(() => Array.from(Object.values(wishes)), [wishes])
const allDirty = useMemo(
() => wishArr.map((w) => w.dirty).reduce((prev, curr) => prev && curr),
[wishArr]
)
useMemo(() => {
if (!allDirty) {
return
}
const id = v4()
setWishes((wishes) => ({
...wishes,
[id]: {
value: result.getValue(createWish(id, '')),
dirty: false,
focus: false,
},
}))
}, [allDirty])
const submit = (wishes: Wish[]) => {
console.log(wishes)
}
return (
<HomeLayout page="home">
<BasePrompt>
{wishArr.map((wish) => (
<CreateWish
key={wish.value.id}
hasFocus={wish.focus}
onFocus={() => {
setWishes((wishes) => ({
...Array.from(Object.values(wishes)) // Get array
.map((w) => ({ ...w, focus: false })) // Reset focus for all
.reduce((obj, cur) => ({ ...obj, [cur.value.id]: cur }), {}), // Translate to object
[wish.value.id]: { ...wish, focus: true },
}))
}}
onSubmit={(wish) => {
setWishes((ws) => ({
...ws,
[wish.id]: { value: wish, dirty: true, focus: true },
}))
}}
wish={wish.value}
/>
))}
<button
type="button"
className="rounded bg-pink-400 py-2 px-4 text-white"
onClick={() =>
submit(wishArr.filter((w) => w.dirty).map((w) => w.value))
}
>
Submit
</button>
</BasePrompt>
</HomeLayout>
)
}
export default HomePage