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 (
{ e.preventDefault() createItem({ variables: { text: text.value, parentId } }) setOpen(false) text.value = '' }} >