vercel / swr

React Hooks for Data Fetching
https://swr.vercel.app
MIT License
30.37k stars 1.21k forks source link

mutate() never calls onSuccess nor onError #2841

Closed rgbskills closed 10 months ago

rgbskills commented 10 months ago

Bug report

Description / Observed Behavior

When using mutate, onSuccess is never called, same for onError

Expected Behavior

onSuccess should be called when a remote mutation has been finished successfully

Repro Steps / Code Example

const handleProductCreate = async (productData) => {
    const currentProducts = data; // Get the current list of products

    const createProduct = async () => {
      try {
        const response = await reqWithToken('/api/admin/products', 'POST', productData);
        return [response, ...currentProducts]; // Add the new product at the beginning of the list
      } catch (error) {
        throw new Error(error);
      }
    }

    try {
      // Optimistically update the local state to add the new product
      const optimisticProducts = [{ ...productData, id: Date.now() }, ...currentProducts];

      // Call the mutate function with the CREATE request
      await mutate(createProduct, {
        optimisticData: optimisticProducts, // Set optimistic data to the updated list
        populateCache: true, // Update the cache with the optimistic data
        revalidate: false, // Disable revalidation after mutation
        rollbackOnError: true, // Rollback to the previous state in case of an error
        onSuccess: async (newData) => {
          console.log("Product successfully created.");
          // Optionally notify the user of successful creation
        }
      });
      // setSelected(newData); // Set the newly created product as selected
    } catch (error) {
      console.error('Error during product creation process:', error);
      // Handle or notify the error appropriately
    }
  };

Additional Context

SWR version. "swr": "^2.2.4",

koba04 commented 10 months ago

mutate doesn't support onSuccess, so it isn't called.

https://swr.vercel.app/docs/mutation#parameters