How can I use the useOptimistic hook with this code any tips?
Unanswered
Burgos Pointer posted this in #help-forum
![Avatar](https://cdn.discordapp.com/embed/avatars/4.png)
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](https://cdn.discordapp.com/embed/avatars/0.png)
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.
- 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](https://cdn.discordapp.com/attachments/1173414667562000394/1174090730441015437/image.png?ex=65665433&is=6553df33&hm=03d7d6d379b4719264eaf81e7692f8b33ccac5d5c54036d6cd0f8c2b6bb93358&)
![Image](https://cdn.discordapp.com/attachments/1173414667562000394/1174090730747207810/image.png?ex=65665433&is=6553df33&hm=2f7dd68e958a318efe2fc5d806f523f37cbab69d17c96510086da26eb2d4c23b&)
![Image](https://cdn.discordapp.com/attachments/1173414667562000394/1174090731154067527/image.png?ex=65665433&is=6553df33&hm=f36c5cfd131959923f36c234d96520a4f23276ce88803df29fa8b52a45bef585&)
currently i'm doing like this in my app and works perfectly
![Image](https://cdn.discordapp.com/attachments/1173414667562000394/1174090993084145714/image.png?ex=65665472&is=6553df72&hm=7f38fd9e256d3387784f392f725176b2d1764816f60313bd091d22bf795821eb&)