react-query#useQuery JavaScript Examples

The following examples show how to use react-query#useQuery. 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: useBlockQuery.js    From akashlytics-deploy with GNU General Public License v3.0 6 votes vote down vote up
export function useBlock(id, options = {}) {
  const { settings } = useSettings();
  return useQuery(QueryKeys.getBlockKey(id), () => getBlock(settings.apiEndpoint, id), {
    refetchInterval: false,
    refetchIntervalInBackground: false,
    refetchOnWindowFocus: false,
    refetchOnReconnect: false,
    ...options
  });
}
Example #3
Source File: useHarrisBenedictCalculator.js    From flame-coach-web with MIT License 6 votes vote down vote up
useHarrisBenedictCalculator = ({ weight, height, gender, age, pal = null, unit = 'kg/cm' }, options) => {
  return useQuery(
    ['getHarrisBenedictCalculator', { weight, height, gender, age, unit, pal }],
    () => getHarrisBenedictCalculator(weight, height, gender, age, unit, pal),
    {
      ...options,
      onError: async (err) => {
        logError('Client',
          'useQuery getHarrisBenedictCalculator',
          'Error:', err);
      }
    });
}
Example #4
Source File: useAllowancesQuery.js    From origin-dollar with MIT License 6 votes vote down vote up
useAllowancesQuery = (account, contracts, options) => {
  return useQuery(
    QUERY_KEYS.Allowances(account),
    () => allowancesService.fetchAllowances(account, contracts),
    {
      enabled: account != null && contracts != null,
      refetchOnWindowFocus: false,
      ...options,
    }
  )
}
Example #5
Source File: index.js    From peppermint with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function ViewNoteBook() {
  const router = useRouter();

  async function getMarkdown() {
    const res = await fetch(`/api/v1/note/${router.query.id}`);
    return res.json();
  }

  const { data, status, error } = useQuery("viewMarkdown", getMarkdown);

  return (
    <div>
      {status === "success" && (
        <>
          <Link href={`/notebook/${data.data.id}/edit`}>
            <button
              type="button"
              className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
            >
              Edit
            </button>
          </Link>

          <div className="mt-4">
            <MD data={data.data.note} />
          </div>
        </>
      )}
    </div>
  );
}
Example #6
Source File: Detail.jsx    From sitepoint-books-firebase with MIT License 6 votes vote down vote up
function ScreenBookDetail() {
  const { id } = useParams()
  const { data, isLoading, error, status } = useQuery(
    ['book', { id }],
    BookService.getOne
  )

  return (
    <>
      <PageHeading title="Book Detail" />
      {error && <Alert type="error" message={error.message} />}
      {isLoading && (
        <Alert
          type="info"
          message="Loading..."
          innerClass="animate animate-pulse"
        />
      )}
      {status === 'success' && <BookDetail book={data} />}
    </>
  )
}
Example #7
Source File: useDynamicInfo.js    From covince with MIT License 6 votes vote down vote up
useInfoQuery = (api_url) => {
  const getInfo = useCallback(async () => {
    const response = await fetch(`${api_url}/info`)
    const info = await response.json()
    info.dates.sort()
    return info
  }, [api_url])
  const { data } = useQuery('info', getInfo, { suspense: true })
  return data
}
Example #8
Source File: useSearch.js    From gardener-site with Mozilla Public License 2.0 6 votes vote down vote up
useSearch = (entity, queryFunction) => {
  const [input, setInput] = useState('');
  const [dataListDefault, setDataListDefault] = useState();
  const [dataList, setDataList] = useState();
  const { isLoading, isError, data, error } = useQuery(
    `${entity}`,
    queryFunction
  );

  setDataList(data);
  setDataListDefault(data);

  const updateInput = input => {
    const filtered = dataListDefault.filter(data => {
      return data.name.toLowerCase().includes(input.toLowerCase());
    });
    setInput(input);
    setUserList(filtered);
  };

  return { isLoading, isError, error, dataList, input, updateInput, entity };
}
Example #9
Source File: useJobProfileData.js    From ui-data-export with Apache License 2.0 6 votes vote down vote up
useJobProfileData = ({
  onSubmit, onCancel, match, errorMessageId, successMessageId,
}) => {
  const ky = useOkapiKy();

  const { data: jobProfileRecord } = useQuery(
    ['data-export', 'job-profile', match.params.id],
    () => ky(`data-export/job-profiles/${match.params.id}`).json()
  );

  const handleSubmit = useProfileHandlerWithCallout({
    errorMessageId,
    successMessageId,
    onAction: onSubmit,
    onActionComplete: onCancel,
    isCanceledAfterError: true,
  });

  return {
    jobProfileRecord,
    handleSubmit,
  };
}
Example #10
Source File: index.js    From Quest with MIT License 6 votes vote down vote up
function ConfluenceDetail({ item, username, password, url, pageSize = 5, filter }) {
  const link = `${_.get(item, "content._links.self")}?expand=body.view`;

  const { data, error } = useQuery(
    link,
    confluenceFetcher({ username, password, baseUrl: url, pageSize, filter })
  );

  if (error) {
    return <p>Failed to load document: {link}</p>;
  }

  if (!data) {
    return <Spinner />;
  }

  return (
    <div className={Classes.RUNNING_TEXT}>
      <H2>{item.content.title}</H2>
      <p>
        <ExternalLink href={url + item.url}>Edit in Confluence</ExternalLink>
      </p>
      <p>
        {item.content?.metadata?.labels.results.map(({ name, id }) => (
          <Tag key={id} round minimal style={{ marginRight: 2, marginLeft: 2 }}>
            {name}
          </Tag>
        ))}
      </p>
      <SafeHtmlElement html={cleanConfluenceHtml(data?.body.view.value, url)} />
    </div>
  );
}
Example #11
Source File: hooks.js    From idena-web with MIT License 6 votes vote down vote up
function useLiveRpc(method, params, {enabled = true, ...options} = {}) {
  const rpcFetcher = useRpcFetcher()

  const lastBlock = useLastBlock({enabled})

  return useQuery([method, params, lastBlock?.hash], rpcFetcher, {
    enabled,
    staleTime: Infinity,
    keepPreviousData: true,
    notifyOnChangeProps: 'tracked',
    ...options,
  })
}
Example #12
Source File: Competition.js    From 4IZ268-2021-2022-ZS with MIT License 6 votes vote down vote up
useSetInfiniteDataStore = (compId) => {

    const autoRefetch = usePersonalSettings((state) => state.autoRefetch)
    const refetchInterval = usePersonalSettings((state) => state.refetchInterval)

    const query = useQuery(
        ['passings', { comp: compId }],
        getLastPassings,
        {
            enabled: !!compId,
            refetchInterval: autoRefetch ? refetchInterval || 15000 : undefined,
        });

    const setLastPassings = useDataStore((state) => state.setLastPassings);

    useEffect(() => {
        if (query.data) {
            if (query.data.status === 'OK') {
                setLastPassings(query.data.passings)
            }
        }
    }, [query.data, setLastPassings])
}
Example #13
Source File: useAllCreatedPrizePools.js    From pooltogether-community-ui with MIT License 6 votes vote down vote up
useAllCreatedPrizePools = () => {
  const { chainId } = useNetwork()
  const readProvider = useReadProvider(chainId)

  return useQuery(
    [QUERY_KEYS.useAllCreatedPrizePools, chainId],
    async () => await getAllCreatedPrizePools(readProvider, chainId),
    // @ts-ignore
    {
      ...NO_REFETCH_QUERY_OPTIONS,
      enabled: chainId && Boolean(readProvider),
      staleTime: Infinity
    }
  )
}
Example #14
Source File: useAccountGovernanceData.js    From pooltogether-governance-ui with MIT License 6 votes vote down vote up
function useAccountGovernanceDataQuery() {
  const { address: usersAddress } = useOnboard()
  const chainId = useGovernanceChainId()
  const error = testAddress(usersAddress)

  const refetchInterval = MAINNET_POLLING_INTERVAL

  return useQuery(
    [QUERY_KEYS.accountGovernanceDataQuery, chainId, usersAddress],
    async () => {
      return getAccountGovernanceData(chainId, usersAddress)
    },
    {
      enabled: Boolean(chainId && usersAddress && !error),
      refetchInterval
    }
  )
}
Example #15
Source File: useCoingeckoTokenInfoQuery.js    From pooltogether-pool-builder-ui with MIT License 6 votes vote down vote up
export function useCoingeckoTokenInfoQuery(address) {
  const { walletChainId } = useWalletNetwork()
  const isMainnet = walletChainId === NETWORK.mainnet

  return useQuery([QUERY_KEYS.coingeckoTokenInfoQuery, address], async () => _getInfo(address), {
    enabled: Boolean(address && isMainnet),
    refetchInterval: false,
    refetchOnWindowFocus: false,
    retry: false
  })
}
Example #16
Source File: V4PoolCard.jsx    From v3-ui with MIT License 6 votes vote down vote up
useDrawBeaconPeriodEndTime = () => {
  const readProvider = useReadProvider(NETWORK.mainnet)
  const [refetchIntervalMs, setRefetchIntervalMs] = useState(sToMs(60 * 2.5))

  const onSuccess = (drawBeaconData) => {
    const { endsAtSeconds } = drawBeaconData
    let refetchIntervalMs = sToMs(endsAtSeconds.toNumber()) - Date.now()
    // Refetch when the period is done
    if (refetchIntervalMs > 0) {
      setRefetchIntervalMs(refetchIntervalMs)
    } else {
      // Otherwise, refetch every 2.5 minutes (1/2 the time for the defender cron job)
      setRefetchIntervalMs(sToMs(60 * 2.5))
    }
  }

  return useQuery(['useDrawBeaconPeriod'], () => getDrawBeaconPeriodEndTime(readProvider), {
    refetchInterval: refetchIntervalMs,
    onSuccess
  })
}
Example #17
Source File: BooksList.jsx    From react-query-3 with GNU General Public License v3.0 6 votes vote down vote up
BooksList = () => {
  const { data, error, isLoading, isError } = useQuery("books", getAllBooks);

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

  if (isError) {
    return <span>Error: {error.message}</span>;
  }

  return (
    <Container>
      <Flex flexDirection="column" alignItems="center">
        {data.map(({ author, title, id }) => (
          <BookItem author={author} title={title} key={id} id={id} />
        ))}
      </Flex>
    </Container>
  );
}
Example #18
Source File: Confirm.jsx    From awesome-react-starter with MIT License 6 votes vote down vote up
Confirm = ({ hash }) => {
  const { status } = useQuery(`confirm/${hash}`, () => confirm(hash));

  return (
    <>
      {status === 'loading' && <Loading />}
      {status === 'error' && (
        <p className="text-red-600 animated fadeIn">Error! Your account was not confirmed.</p>
      )}
      {status === 'success' && (
        <p className="text-green-700 animated fadeIn">Success! Your account was confirmed.</p>
      )}
    </>
  );
}
Example #19
Source File: useBalancesQuery.js    From akashlytics-deploy with GNU General Public License v3.0 5 votes vote down vote up
export function useBalances(address, options) {
  const { settings } = useSettings();
  return useQuery(QueryKeys.getBalancesKey(address), () => getBalances(settings.apiEndpoint, address), options);
}