TanStackT
TanStack3y ago
1 reply
scornful-crimson

useMutation not updating

Is this correct way to use mutate?

{
  "states": [
    {
      "id": 1,
      "value": true
    },
    {
      "id": 2,
      "value": false
    },
    {
      "id": 3,
      "value": true
    }
  ]
}

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import axios from 'axios'

const App = () => {
  const queryClient = useQueryClient()

  const { data } = useQuery({
    queryKey: ['states'],
    queryFn: async () => {
      const response = await axios.get('http://localhost:3000/states')
      return response.data
    }
  })

  const { mutate } = useMutation({
    mutationKey: ['states'],
    mutationFn: async (updatedData) => {
      console.log(updatedData)
      await axios.put(
        `http://localhost:3000/states/${updatedData.id}`,
        updatedData
      )
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['states'] })
  })

  const handleCheckboxChange = async (id) => {
    const newData = data?.map((state) =>
      state.id === id ? { ...state, value: !state.value } : state
    )

    const updatedData = newData.find((state) => state.id === id)

    if (updatedData) {
      await mutate(updatedData)
    }
  }

  return (
    <div className='vh-100 bg-info d-flex justify-content-center align-items-center'>
      <div className='d-flex align-items-center justify-content-center'>
        {data?.map((state) => (
          <input
            key={state.id}
            type='checkbox'
            className='form-check-input m-2'
            value={state.value}
            checked={state.value}
            onChange={() => handleCheckboxChange(state.id)}
          />
        ))}
      </div>
    </div>
  )
}

export default App
Was this page helpful?