import { useQuery, gql, useMutation } from '@apollo/client'
import { useState } from 'react'
import { useSession } from 'next-auth/client'
import styles from '../styles/index.module.css'
import Layout from '../components/layout'
function Users () {
const { loading, error, data } = useQuery(gql`{ users { id, name } }`)
if (error) return
Failed to load
if (loading) return Loading...
const { users } = data
return (
{users.map(user => (
{user.name}
))}
)
}
function NewItem ({ parentId }) {
const [session] = useSession()
const [createItem] = useMutation(
gql`
mutation CreateItem($text: String!, $parentId: ID) {
createItem(text: $text, parentId: $parentId) {
id
}
}`, {
update (cache, { data: { createItem } }) {
cache.modify({
fields: {
items (existingItems = [], { readField }) {
const newItemRef = cache.writeFragment({
data: createItem,
fragment: gql`
fragment NewItem on Item {
id
user {
name
}
text
depth
}
`
})
for (let i = 0; i < existingItems.length; i++) {
if (readField('id', existingItems[i]) === parentId) {
return [...existingItems.slice(0, i), newItemRef, ...existingItems.slice(i)]
}
}
return [newItemRef, ...existingItems]
}
}
})
}
})
const [open, setOpen] = useState(false)
if (!session) return null
if (!open) {
return (
setOpen(true)}>
{parentId ? 'reply' : 'submit'}
)
}
let text
return (
)
}
function Items () {
const { loading, error, data } = useQuery(
gql`
{ items {
id
user {
name
}
text
depth
} }`
)
if (error) return Failed to load
if (loading) return Loading...
const { items } = data
return (
<>
{items.map(item => (
{item.user.name} : {item.text}
))}
>
)
}
export default function Index () {
return (
)
}