In Next.js, you can use the useMutation
hook provided by a library like react-query
or swr
. Here, I'll show you an example using react-query
. Make sure you have react-query
installed in your project:
bashnpm install react-query
# or
yarn add react-query
Now, you can use the useMutation
hook to handle data mutation, such as updating data. Here's an example:
react-query
client:jsx// pages/_app.js
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
const queryClient = new QueryClient();
function MyApp({ Component, pageProps }) {
return (
<QueryClientProvider client={queryClient}>
<Component {...pageProps} />
<ReactQueryDevtools />
</QueryClientProvider>
);
}
export default MyApp;
useMutation
hook for updating data:jsx// components/UpdateDataForm.js
import { useMutation } from 'react-query';
const updateData = async (newData) => {
// Perform your API call or data update logic here
const response = await fetch('/api/update-data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newData),
});
if (!response.ok) {
throw new Error('Update failed');
}
return response.json();
};
const UpdateDataForm = ({ initialData }) => {
const mutation = useMutation(updateData);
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const newData = Object.fromEntries(formData.entries());
try {
await mutation.mutateAsync(newData);
// Data updated successfully
} catch (error) {
console.error('Update failed:', error.message);
}
};
return (
<form onSubmit={handleSubmit}>
{/* Your form inputs go here */}
<button type="submit" disabled={mutation.isLoading}>
{mutation.isLoading ? 'Updating...' : 'Update Data'}
</button>
</form>
);
};
export default UpdateDataForm;
UpdateDataForm
component in your page:jsx// pages/index.js
import UpdateDataForm from '../components/UpdateDataForm';
const Home = () => {
return (
<div>
<h1>Next.js with useMutation</h1>
<UpdateDataForm />
</div>
);
};
export default Home;
In this example, the useMutation
hook from react-query
is used to handle the asynchronous update of data. The mutation.mutateAsync
function is called when the form is submitted, and it automatically handles loading states, error handling, and updating the cache.
Remember to adapt this example to your specific use case and API endpoints. The /api/update-data
endpoint is just a placeholder; replace it with your actual API endpoint for updating data.