react-query#useMutation JavaScript Examples

The following examples show how to use react-query#useMutation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: List.jsx    From sitepoint-books-firebase with MIT License 7 votes vote down vote up
function ScreenAuthorList() {
  const { data, isLoading, error, status } = useQuery(
    'authors',
    AuthorService.getAll
  )

  const queryClient = useQueryClient()

  const deleteMutation = useMutation((id) => AuthorService.remove(id), {
    onSuccess: () => {
      queryClient.invalidateQueries('authors')
    },
  })

  const deleteAction = async (id) => {
    deleteMutation.mutateAsync(id)
  }

  return (
    <>
      <PageHeading title="Author List" />
      <div className="mt-12">
        {error && <Alert type="error" message={error.message} />}
        {isLoading && (
          <Alert
            type="info"
            message="Loading..."
            innerClass="animate animate-pulse"
          />
        )}
        {status === 'success' && (
          <AuthorList data={data} deleteAction={deleteAction} />
        )}
      </div>
    </>
  )
}
Example #2
Source File: useDeleteAppointmentsCoach.js    From flame-coach-web with MIT License 6 votes vote down vote up
useDeleteAppointmentClient = () => {
  const {
    mutate,
    isLoading
  } = useMutation(deleteAppointment);

  return {
    mutate,
    isLoading
  };
}
Example #3
Source File: CreateBook.jsx    From react-query-3 with GNU General Public License v3.0 6 votes vote down vote up
CreateBook = () => {
  const history = useHistory()
  const { mutateAsync, isLoading } = useMutation(createBook)

  const onFormSubmit = async (data) => {
    await mutateAsync({...data})
    history.push("/")
  }
  return (
    <Container>
      <Box
        sx={{
          py: 3,
        }}
      >
        <Heading sx={{ marginBottom: 3 }}>Create New Book</Heading>
        <BookForm onFormSubmit={onFormSubmit} isLoading={isLoading}/>
      </Box>
    </Container>
  );
}
Example #4
Source File: BookItem.jsx    From react-query-3 with GNU General Public License v3.0 6 votes vote down vote up
BookItem = ({id, title, author }) => {
  const queryClient = useQueryClient()
  const { mutateAsync, isLoading } = useMutation(removeBook)

  const remove = async () => {
    await mutateAsync(id)
    queryClient.invalidateQueries('books')
  }

  return (
    <Flex key={id} p={3} width="100%" alignItems="center">
      <StyledLink as={RouterLink} to={`/update-book/${id}`} mr="auto">{title}</StyledLink>
      <Text>{author}</Text>
      <Button onClick={remove} ml="5">
        { isLoading ? <Loader type="ThreeDots" color="#fff" height={10} /> : "Remove" }
      </Button>
    </Flex>
  );
}
Example #5
Source File: ScriptCallHistoryContext.js    From sdk with Apache License 2.0 6 votes vote down vote up
useScriptCallMutation = (folderPath, scriptCall, params, opts, onSuccess, onError) => {
  const { addScriptCall } = useScriptCallHistoryContext();

  const scriptFullPath = folderPath ? `${folderPath}/${scriptCall?.script}` : scriptCall?.script;
  const postData = {
    script: scriptFullPath,
    function: scriptCall?.function,
    opts,
    params,
  };

  const addScriptCallResponse = (response) => {
    addScriptCall({
      ...postData,
      date: new Date(),
      data: response?.data,
      error: response?.error,
      logs: response?.logs,
    });
  };

  return useMutation({
    mutationFn: () => axios.post('/api/action', postData),
    onSuccess: (res) => {
      addScriptCallResponse(res);
      if (onSuccess) {
        onSuccess(res);
      }
    },
    onError: (err) => {
      addScriptCallResponse(err?.response?.data);
      if (onError) {
        onError(err);
      }
    },
  });
}
Example #6
Source File: hooks.js    From idena-web with MIT License 6 votes vote down vote up
export function useReplenishStake({onSuccess, onError}) {
  const {coinbase, privateKey} = useAuthState()

  const mutation = useMutation(
    async ({amount}) => {
      const rawTx = await getRawTx(
        TxType.ReplenishStakeTx,
        coinbase,
        coinbase,
        amount
      )

      return sendRawTx(
        `0x${new Transaction()
          .fromHex(rawTx)
          .sign(privateKey)
          .toHex()}`
      )
    },
    {
      onSuccess,
      onError,
    }
  )

  return {
    submit: mutation.mutate,
  }
}
Example #7
Source File: List.jsx    From sitepoint-books-firebase with MIT License 6 votes vote down vote up
function ScreenCategoryList() {
  const { data, isLoading, error, status } = useQuery(
    'books',
    CategoryService.getAll
  )

  const queryClient = useQueryClient()

  const deleteMutation = useMutation((id) => CategoryService.remove(id), {
    onSuccess: () => {
      queryClient.invalidateQueries('categories')
    },
  })

  const deleteAction = async (id) => {
    deleteMutation.mutateAsync(id)
  }

  return (
    <>
      <PageHeading title="Category List" />
      <div className="mt-12">
        {error && <Alert type="error" message={error.message} />}
        {isLoading && (
          <Alert
            type="info"
            message="Loading..."
            innerClass="animate animate-pulse"
          />
        )}
        {status === 'success' && (
          <CategoryList data={data} deleteAction={deleteAction} />
        )}
      </div>
    </>
  )
}
Example #8
Source File: List.jsx    From sitepoint-books-firebase with MIT License 6 votes vote down vote up
function ScreenBookList() {
  const { data, isLoading, error, status } = useQuery(
    'books',
    BookService.getAll
  )

  const queryClient = useQueryClient()

  const deleteMutation = useMutation((id) => BookService.remove(id), {
    onSuccess: () => {
      queryClient.invalidateQueries('books')
    },
  })

  const deleteAction = async (id) => {
    deleteMutation.mutateAsync(id)
  }

  return (
    <>
      <PageHeading title="Book List" />
      <div className="mt-12">
        {error && <Alert type="error" message={error.message} />}
        {isLoading && (
          <Alert
            type="info"
            message="Loading..."
            innerClass="animate animate-pulse"
          />
        )}
        {status === 'success' && (
          <BookList data={data} deleteAction={deleteAction} />
        )}
      </div>
    </>
  )
}
Example #9
Source File: useAddAppointmentClient.js    From flame-coach-web with MIT License 6 votes vote down vote up
useAddAppointmentClient = () => {
  const {
    mutate,
    isLoading
  } = useMutation(addAppointment);

  return {
    mutate,
    isLoading
  };
}
Example #10
Source File: useInviteClient.js    From flame-coach-web with MIT License 6 votes vote down vote up
useInviteClient = () => {
  const {
    mutate,
    isLoading
  } = useMutation(inviteClient);

  return {
    mutate,
    isLoading
  };
}
Example #11
Source File: hooks.js    From idena-web with MIT License 5 votes vote down vote up
function useDeployAdContract({onBeforeSubmit, onSubmit, onError}) {
  const {encodeAd} = useProtoProfileEncoder()

  const coinbase = useCoinbase()

  const privateKey = usePrivateKey()

  const {data: deployAmount} = useDeployContractAmount()

  return useMutation(
    async ad => {
      const unpublishedVoting = buildAdReviewVoting({title: ad.title})

      const {cid} = await sendToIpfs(
        encodeAd({
          ...ad,
          version: 0,
          votingParams: unpublishedVoting,
        }),
        {
          from: coinbase,
          privateKey,
        }
      )

      const voting = {
        ...unpublishedVoting,
        adCid: cid,
      }

      const deployPayload = prependHex(
        bytes.toHex(
          new DeployContractAttachment(
            bytes.fromHex('0x02'),
            argsToSlice(buildContractDeploymentArgs(voting)),
            3
          ).toBytes()
        )
      )

      const estimateDeployResult = await estimateSignedTx(
        {
          type: TxType.DeployContractTx,
          from: coinbase,
          amount: deployAmount,
          payload: deployPayload,
        },
        privateKey
      )

      const hash = await sendSignedTx(
        {
          type: TxType.DeployContractTx,
          from: coinbase,
          amount: deployAmount,
          payload: deployPayload,
          maxFee: Number(estimateDeployResult.txFee) * 1.1,
        },
        privateKey
      )

      return {
        cid,
        contract: estimateDeployResult.receipt?.contract,
        hash,
        voting,
      }
    },
    {
      onMutate: onBeforeSubmit,
      onSuccess: onSubmit,
      onError,
    }
  )
}
Example #12
Source File: UpdateBook.jsx    From react-query-3 with GNU General Public License v3.0 5 votes vote down vote up
UpdateBook = () => {
  const { id } = useParams()
  const history = useHistory()
  const { data, error, isLoading, isError } = useQuery(["book", { id }], getBook);
  const { mutateAsync, isLoading: isMutating } = useMutation(updateBook)

  const onFormSubmit = async (formData) => {
    await mutateAsync({...formData, id})
    history.push("/")
  }

  if (isLoading) {
    return (
      <Container>
        <Flex py="5" justifyContent="center">
          <Loader type="ThreeDots" color="#cccccc" height={30} />
        </Flex>
      </Container>
    );
  }

  if (isError) {
    return (
      <Container>
        <Flex py="5" justifyContent="center">
          Error: {error.message}
        </Flex>
      </Container>
    );
  }

  return (
    <Container>
      <Box
        sx={{
          py: 3,
        }}
      >
        <Heading sx={{ marginBottom: 3 }}>Update Book</Heading>
        <BookForm defaultValues={data} onFormSubmit={onFormSubmit} isLoading={isMutating}/>
      </Box>
    </Container>
  );
}
Example #13
Source File: useEditAppointmentsCoach.js    From flame-coach-web with MIT License 5 votes vote down vote up
useEditAppointmentClient = () => {
  return useMutation(editAppointment);
}
Example #14
Source File: useUpdateDoc.js    From rainbow-modules with MIT License 5 votes vote down vote up
useUpdateDoc = (opts = {}) => {
    const app = useFirebaseApp();
    return useMutation(({ path, data }) => {
        return app.firestore().doc(path).update(data);
    }, opts);
}
Example #15
Source File: useSetDoc.js    From rainbow-modules with MIT License 5 votes vote down vote up
useSetDoc = (opts = {}) => {
    const app = useFirebaseApp();
    return useMutation(({ path, data, options }) => {
        return app.firestore().doc(path).set(data, options);
    }, opts);
}
Example #16
Source File: useRemoveDoc.js    From rainbow-modules with MIT License 5 votes vote down vote up
useRemoveDoc = (opts = {}) => {
    const app = useFirebaseApp();
    return useMutation((path) => {
        return app.firestore().doc(path).delete();
    }, opts);
}
Example #17
Source File: useAddDoc.js    From rainbow-modules with MIT License 5 votes vote down vote up
useAddDoc = (path, opts = {}) => {
    const app = useFirebaseApp();
    return useMutation((data) => {
        return app.firestore().collection(path).add(data);
    }, opts);
}
Example #18
Source File: useAddWeightClient.js    From flame-coach-web with MIT License 5 votes vote down vote up
useAddWeightClient = () => {
  const { mutate, isLoading } = useMutation(addWeightClient);

  return { mutate, isLoading };
}
Example #19
Source File: hooks.js    From idena-web with MIT License 5 votes vote down vote up
export function useBurnAd({onBeforeSubmit, onMined, onError}) {
  const {encodeAdTarget} = useProtoProfileEncoder()

  const coinbase = useCoinbase()

  const privateKey = usePrivateKey()

  const {data: hash, mutate, reset} = useMutation(
    async ({ad, amount}) =>
      sendSignedTx(
        {
          type: TxType.BurnTx,
          from: coinbase,
          amount,
          payload: prependHex(
            new BurnAttachment({
              key: new AdBurnKey({
                cid: ad.cid,
                target: encodeAdTarget(ad),
              }).toHex(),
            }).toHex()
          ),
        },
        privateKey
      ),
    {
      onBeforeSubmit,
      onError,
    }
  )

  const {data: txData} = useTrackTx(hash, {
    onMined,
    onError,
  })

  return {
    data: hash,
    txData,
    submit: mutate,
    reset,
  }
}
Example #20
Source File: hooks.js    From idena-web with MIT License 5 votes vote down vote up
export function usePublishAd({onBeforeSubmit, onMined, onError}) {
  const {encodeAdTarget, encodeProfile} = useProtoProfileEncoder()

  const coinbase = useCoinbase()

  const privateKey = usePrivateKey()

  const {data, mutate} = useMutation(
    async ad => {
      const profileAds = await fetchProfileAds(coinbase)

      const encodedProfile = encodeProfile({
        ads: [
          ...profileAds,
          {
            target: encodeAdTarget(ad),
            cid: ad.cid,
            contract: ad.contract,
            author: ad.author ?? coinbase,
          },
        ],
      })

      const {cid: profileCid, hash: sendToIpfsHash} = await sendToIpfs(
        encodedProfile,
        {
          from: coinbase,
          privateKey,
        }
      )

      const changeProfileHash = await sendSignedTx(
        {
          type: TxType.ChangeProfileTx,
          from: coinbase,
          payload: prependHex(
            new ChangeProfileAttachment({
              cid: CID.parse(profileCid).bytes,
            }).toHex()
          ),
        },
        privateKey
      )

      return {
        profileCid,
        sendToIpfsHash,
        changeProfileHash,
      }
    },
    {
      onMutate: onBeforeSubmit,
      onError,
    }
  )

  const {data: txData} = useTrackTx(data?.changeProfileHash, {onMined, onError})

  return {
    data,
    txData,
    submit: mutate,
  }
}
Example #21
Source File: hooks.js    From idena-web with MIT License 5 votes vote down vote up
function useStartAdVoting({onError}) {
  const coinbase = useCoinbase()

  const privateKey = usePrivateKey()

  const {data: startAmount} = useStartAdVotingAmount()

  return useMutation(
    async startParams => {
      const payload = prependHex(
        bytes.toHex(
          new CallContractAttachment(
            'startVoting',
            argsToSlice(buildContractDeploymentArgs(startParams?.voting)),
            3
          ).toBytes()
        )
      )

      const estimateResult = await estimateSignedTx(
        {
          type: TxType.CallContractTx,
          from: coinbase,
          to: startParams?.contract,
          amount: startAmount,
          payload,
        },
        privateKey
      )

      return sendSignedTx(
        {
          type: TxType.CallContractTx,
          from: coinbase,
          to: startParams?.contract,
          amount: startAmount,
          payload,
          maxFee: Number(estimateResult.txFee) * 1.1,
        },
        privateKey
      )
    },
    {onError}
  )
}
Example #22
Source File: apiTokenForm.js    From gardener-site with Mozilla Public License 2.0 5 votes vote down vote up
TokenForm = () => {

   const mutation = useMutation("apiToken", updateApiToken) 

    return (
        <div>
            <h1>
                Enter Your API Token
            </h1>
            <p>
                How? Follow<a src="http://dogegarden.net">this.</a>
            </p>
            <Formik 
                initialValues = {{apiToken = ''}}
                validate = {values => {
                    const errors = {}
                    if(!values.apiToken) {
                        errors.apiToken = 'API Token is Required'
                    } else if(!/[^a-zA-Z0-9]+/g.test(values.apiToken)) {
                        errors.apiToken = 'Invalid API Token'
                    }
                    return errors
                }}
                onSubmit = {(values, { setSubmitting, resetForm }) => {
                    setSubmitting(true)
                    mutation.mutate({ apiToken: values.apiToken })
                    setSubmitting(false)
                    resetForm()
                }}
            >
                {({
                    values,
                    errors,
                    handleChange,
                    handleBlur,
                    handleSubmit,
                    isSubmitting
                }) => (
                    <form onSubmit={handleSubmit}>
                    <input
                        type="apiToken"
                        name="Token"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.apiToken}
                    />
                    {errors.apiToken && touched.apiToken && errors.apiToken}
                    <button type="submit" disabled={isSubmitting}>
                        Submit
                    </button>
                    </form>
                )}
            </Formik>
        </div>
    )
}
Example #23
Source File: useDeleteWeightClient.js    From flame-coach-web with MIT License 5 votes vote down vote up
useDeleteWeightClient = () => {
  const { mutate, isLoading } = useMutation(deleteWeightClient);

  return { mutate, isLoading };
}
Example #24
Source File: Form.jsx    From sitepoint-books-firebase with MIT License 5 votes vote down vote up
function ScreenCategoryForm() {
  let { id } = useParams()
  const { data, isLoading, error, status } = useQuery(
    ['category', { id }],
    CategoryService.getOne
  )
  const queryClient = useQueryClient()

  const saveData = (data) => {
    if (id) {
      return CategoryService.update(id, data)
    } else {
      CategoryService.create(data)
    }
  }

  const mutation = useMutation((data) => saveData(data), {
    onSuccess: () => {
      if (id) queryClient.invalidateQueries(['category', { id }])
    },
  })

  const { isSuccess } = mutation

  const onSubmit = async (submittedData) => {
    mutation.mutate(submittedData)
  }

  if (isSuccess) {
    return <Redirect to="/category" />
  }

  if (!id) {
    return (
      <>
        <PageHeading title="Create Category" />
        <div className="mt-12">
          <CategoryForm values={{ cover: 'nocover' }} action={onSubmit} />
        </div>
      </>
    )
  }

  return (
    <>
      <PageHeading title="Edit Category" />
      <div className="mt-12">
        {error && <Alert type="error" message={error.message} />}
        {isLoading && (
          <Alert
            type="info"
            message="Loading..."
            innerClass="animate animate-pulse"
          />
        )}
        {status === 'success' && (
          <CategoryForm values={data} action={onSubmit} />
        )}
      </div>
    </>
  )
}
Example #25
Source File: Form.jsx    From sitepoint-books-firebase with MIT License 5 votes vote down vote up
function ScreenAuthorForm() {
  const { id } = useParams()
  const { data, isLoading, error, status } = useQuery(
    ['author', { id }],
    AuthorService.getOne
  )

  const queryClient = useQueryClient()

  const saveData = (data) => {
    if (id) {
      return AuthorService.update(id, data)
    } else {
      AuthorService.create(data)
    }
  }

  const mutation = useMutation((data) => saveData(data), {
    onSuccess: () => {
      if (id) queryClient.invalidateQueries(['author', { id }])
    },
  })

  const { isSuccess } = mutation

  const onSubmit = async (submittedData) => {
    mutation.mutate(submittedData)
  }

  if (isSuccess) {
    return <Redirect to="/author" />
  }

  if (!id) {
    return (
      <>
        <PageHeading title="Create Author" />
        <div className="mt-12">
          {error && <Alert type="error" message={error.message} />}
          <AuthorForm submit={onSubmit} />
        </div>
      </>
    )
  }

  return (
    <>
      <PageHeading title="Edit Author" />
      <div className="mt-12">
        {error && <Alert type="error" message={error.message} />}
        {isLoading && (
          <Alert
            type="info"
            message="Loading..."
            innerClass="animate animate-pulse"
          />
        )}
        {status === 'success' && <AuthorForm values={data} submit={onSubmit} />}
      </div>
    </>
  )
}
Example #26
Source File: useUpdateActivationKey.js    From sed-frontend with Apache License 2.0 5 votes vote down vote up
useUpdateActivationKey = () => {
  return useMutation(activationKeyMutation);
}
Example #27
Source File: useDeleteActivationKey.js    From sed-frontend with Apache License 2.0 5 votes vote down vote up
useDeleteActivationKey = () => {
  return useMutation(deleteActivationKeyMutation);
}
Example #28
Source File: useCreateActivationKey.js    From sed-frontend with Apache License 2.0 5 votes vote down vote up
useCreateActivationKey = () => {
  return useMutation(activationKeyMutation);
}
Example #29
Source File: index.js    From flame-coach-web with MIT License 5 votes vote down vote up
Settings = ({
  customerEmail
}) => {

  const [notification, setNotification] = useState({
    enable: false,
    message: '',
    level: 'INFO'
  });

  const updateNotificationHandler = (enable, message, level) => {
    setNotification({
      enable,
      message,
      level
    });
  };

  const updatePasswordMutation = useMutation(({
    email,
    oldPassword,
    newPassword
  }) => updatePassword(email, oldPassword, newPassword));

  return (
    <Page
      title="Settings"
      isError={false}
      isLoading={false}
    >
      <Box>
        <Password
          notification={notification}
          updateNotificationHandler={updateNotificationHandler}
          updatePasswordHandler={(oldPassword, newPassword, newPasswordConfirmation) => {
            if (newPassword === newPasswordConfirmation) {
              updatePasswordMutation.mutate({
                email: customerEmail,
                oldPassword,
                newPassword
              }, {
                onError: async (error) => {
                  logError('Settings', 'updatePassword', 'Error Details:', error.response.data.detail);
                  const errorCode = ErrorMessage.fromCode(error.response.data.code);
                  updateNotificationHandler(true, errorCode.msg, errorCode.level);
                },
                onSuccess: async () => {
                  const infoCode = InfoMessage.CODE_2003;
                  updateNotificationHandler(true, infoCode.msg, infoCode.level);
                }
              });
            } else {
              const errorCode = ErrorMessage.CODE_0005;
              updateNotificationHandler(true, errorCode.msg, errorCode.level);
            }
          }}
        />
      </Box>
    </Page>
  );
}