T
TanStack10mo ago
fascinating-indigo

useMutation for creating object to use with POST

i am trying to make a simple input field that takes an input and on a button click / submit it adds the data to an object so that it can be used with useMutation to send it with a POST request. i am quite stuck as i cannot really find a good source yet how to handle this (might also be that i cannot formualte the qeustion correctly) i tried doing it like this post on Stackoverflow but not getting anywhere really i think
2 Replies
fascinating-indigo
fascinating-indigoOP10mo ago
my code looks like this (i have it already wrapped with the provider elsewhere as i can make get requests with the useQuery)
const ManageProducts: React.FC = () => {
const [title, setTitle] = useState('');
const [error, setError] = useState<string | null>(null);

const queryClient = useQueryClient();

const addProductMutation = useMutation(
async (dataToPost: { title: string }) => {

const response = await sdk.admin.product.create({
title: dataToPost.title,

});

console.log('Product added:', response);
return response;
},
{
onSuccess: () => {
queryClient.invalidateQueries(['admin-products']);
setTitle('');
},
onError: (error) => {
console.error('Error adding product:', error);
setError('Error adding product');
},
}
);

const handleAddProduct = () => {
setError(null);
addProductMutation.mutate({ title });
};

return (
<Gutter>
<div>
<h2>Add Product</h2>
{error && <div>Error: {error}</div>}
<TextInput
label="Title"
value={title}
onChange={(e: any) => setTitle(e.target.value)}
path="title"
/>


<Button onClick={handleAddProduct}>Add Product</Button>

</div>
</Gutter>
);
const ManageProducts: React.FC = () => {
const [title, setTitle] = useState('');
const [error, setError] = useState<string | null>(null);

const queryClient = useQueryClient();

const addProductMutation = useMutation(
async (dataToPost: { title: string }) => {

const response = await sdk.admin.product.create({
title: dataToPost.title,

});

console.log('Product added:', response);
return response;
},
{
onSuccess: () => {
queryClient.invalidateQueries(['admin-products']);
setTitle('');
},
onError: (error) => {
console.error('Error adding product:', error);
setError('Error adding product');
},
}
);

const handleAddProduct = () => {
setError(null);
addProductMutation.mutate({ title });
};

return (
<Gutter>
<div>
<h2>Add Product</h2>
{error && <div>Error: {error}</div>}
<TextInput
label="Title"
value={title}
onChange={(e: any) => setTitle(e.target.value)}
path="title"
/>


<Button onClick={handleAddProduct}>Add Product</Button>

</div>
</Gutter>
);
like-gold
like-gold10mo ago
Hey there. I'm a little lost on what you are trying to accomplish and why this isn't working. Can you explain what the code above it doing wrong, what the expectation is, and what is currently happening?

Did you find this page helpful?