How can I use the useOptimistic hook in this code

import { revalidateTag } from 'next/cache'
import { User } from '../typings'

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

const users: User[] = await res.json()

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://655112ea7d203ab6626e818d.mockapi.io/users', {
method: 'POST',
body: JSON.stringify(newUser),
headers: {
'Content-Type': 'application/json',
},
})
revalidateTag('users')
}

return (
<main>
<h1 className='text-3xl font-bold text-center'>Users Warehouse</h1>

<form
action={addUserToDatabase}
className='flex flex-col gap-5 max-w-xl mx-auto p-5'
>
<input
name='username'
type='text'
className='border border-gray-300 p-2 rounded-md'
placeholder="Enter User's username..."
/>
<input
name='city'
type='text'
className='border border-gray-300 p-2 rounded-md'
placeholder="Enter User's city..."
/>
<button className='border bg-blue-500 text-white p-2 rounded-md'>
Add Product
</button>
</form>

<div className='flex flex-wrap gap-5'>
{users.map((user) => {
return (
<div key={user.id} className='p-5 shadow'>
<p>{user.username}</p>
<p>{user.city}</p>
</div>
)
})}
</div>
</main>
)
}
import { revalidateTag } from 'next/cache'
import { User } from '../typings'

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

const users: User[] = await res.json()

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://655112ea7d203ab6626e818d.mockapi.io/users', {
method: 'POST',
body: JSON.stringify(newUser),
headers: {
'Content-Type': 'application/json',
},
})
revalidateTag('users')
}

return (
<main>
<h1 className='text-3xl font-bold text-center'>Users Warehouse</h1>

<form
action={addUserToDatabase}
className='flex flex-col gap-5 max-w-xl mx-auto p-5'
>
<input
name='username'
type='text'
className='border border-gray-300 p-2 rounded-md'
placeholder="Enter User's username..."
/>
<input
name='city'
type='text'
className='border border-gray-300 p-2 rounded-md'
placeholder="Enter User's city..."
/>
<button className='border bg-blue-500 text-white p-2 rounded-md'>
Add Product
</button>
</form>

<div className='flex flex-wrap gap-5'>
{users.map((user) => {
return (
<div key={user.id} className='p-5 shadow'>
<p>{user.username}</p>
<p>{user.city}</p>
</div>
)
})}
</div>
</main>
)
}
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server