Next.js Discord

Discord Forum

How can I use the useOptimistic hook with this code any tips?

Unanswered
Burgos Pointer posted this in #help-forum
Open in Discord
Avatar
Burgos PointerOP
import { revalidateTag } from 'next/cache'
import { User } from '../typings'
import { useOptimistic } from 'react'

export default async function Home() {
  const res = await fetch('https://xxx.mockapi.io/users', {
    cache: 'no-cache',
    next: {
      tags: ['users'],
    },
  })

  const users: User[] = await res.json()
  const [optimisticUsers, setOptimisticUsers] = useOptimistic(users)

  const addUserToDatabase = async (e: FormData) => {
    'use server'
    const username = e.get('username')?.toString()
    const city = e.get('city')?.toString()

    if (!username || !city) return

    const newUser = {
      username,
      city,
    }

    await fetch('https://xxx.mockapi.io/users', {
      method: 'POST',
      body: JSON.stringify(newUser),
      headers: {
        'Content-Type': 'application/json',
      },
    })
    revalidateTag('users')
  }
return (
// ... code 
  )
}

2 Replies

Avatar
Tan
I would do like this:
- the Home page is fetching data on server side and passing to client component "UserList"
- the client component is adding users with useOptimistic and useTransition
- add try and catch to server action, and separate to its own file.
Image
Image
Image
currently i'm doing like this in my app and works perfectly
Image