T
TanStack4y ago
genetic-orange

Struggling with basic use of useMutation

My app is not updating when i call useMutation on the button click, i have to refresh the page.
// - Fetch todos from API
async function getUsers() {
const response = await fetch(
'https://api-for-personal-projects.vercel.app/api/contacts'
)
return response.json()
}

//- Main component
interface TodosProps {
className?: string
}

export default function Todos({ className }: TodosProps) {
const queryClient = new QueryClient()

const { data, isLoading, isError } = useQuery(['users'], getUsers)

console.log('data', data)

const useUpdateUsers = useMutation(
(newUser: any) => {
return axios.post(
'https://api-for-personal-projects.vercel.app/api/contacts',
newUser
)
},
{
onSuccess: () => {
// refetch users list
queryClient.invalidateQueries(['users'])
}
}
)

if (isLoading) {
return <div>Loading...</div>
}

if (isError || !Array.isArray(data)) {
return <div>Error</div>
}
return (
<div className={className}>
<button
className="my-2 font-bold"
onClick={() =>
useUpdateUsers.mutate({
id: 54,
firstName: 'david',
lastName: 'Adesanya',
dateOfBirth: '1985-03-15T00:00:00',
school: 'Torquay Boys',
phoneNumber: '01803 123456'
})
}
>
Add User
</button>
{data.map((user: any) => (
<div key={user.id}>{`${user.firstName} ${user.lastName}`}</div>
))}
</div>
)
}
// - Fetch todos from API
async function getUsers() {
const response = await fetch(
'https://api-for-personal-projects.vercel.app/api/contacts'
)
return response.json()
}

//- Main component
interface TodosProps {
className?: string
}

export default function Todos({ className }: TodosProps) {
const queryClient = new QueryClient()

const { data, isLoading, isError } = useQuery(['users'], getUsers)

console.log('data', data)

const useUpdateUsers = useMutation(
(newUser: any) => {
return axios.post(
'https://api-for-personal-projects.vercel.app/api/contacts',
newUser
)
},
{
onSuccess: () => {
// refetch users list
queryClient.invalidateQueries(['users'])
}
}
)

if (isLoading) {
return <div>Loading...</div>
}

if (isError || !Array.isArray(data)) {
return <div>Error</div>
}
return (
<div className={className}>
<button
className="my-2 font-bold"
onClick={() =>
useUpdateUsers.mutate({
id: 54,
firstName: 'david',
lastName: 'Adesanya',
dateOfBirth: '1985-03-15T00:00:00',
school: 'Torquay Boys',
phoneNumber: '01803 123456'
})
}
>
Add User
</button>
{data.map((user: any) => (
<div key={user.id}>{`${user.firstName} ${user.lastName}`}</div>
))}
</div>
)
}
2 Replies
exotic-emerald
exotic-emerald4y ago
Hi your query client is recreated at each render since inside Todos. Move the creation outside and should be good
genetic-orange
genetic-orangeOP4y ago
thank you!

Did you find this page helpful?