How to use the react-query.useQuery function in react-query

To help you get started, we’ve selected a few react-query examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tannerlinsley / react-query / examples / sandbox / src / index.app.js View on Github external
function EditTodo({ editingIndex, setEditingIndex }) {
  // Don't attempt to query until editingIndex is truthy
  const {
    data,
    isLoading,
    isFetching,
    error,
    failureCount,
    refetch
  } = useQuery(
    editingIndex !== null && ["todo", { id: editingIndex }],
    fetchTodoById
  );

  const [todo, setTodo] = React.useState(data);

  React.useEffect(() => {
    if (editingIndex !== null && data) {
      console.log(data);
      setTodo(data);
    } else {
      setTodo();
    }
  }, [data, editingIndex]);

  const [mutate, mutationState] = useMutation(patchTodo, {
github tannerlinsley / react-query / examples / optimistic-updates / pages / index.js View on Github external
export default () => {
  const [text, setText] = React.useState('')
  const { data, isLoading, isFetching } = useQuery('todos', () =>
    fetch('/api/data')
  )

  const [mutatePostTodo] = useMutation(
    text =>
      fetch('/api/data', {
        method: 'POST',
        body: JSON.stringify({ text }),
      }),
    {
      refetchQueries: ['todos'],
      // to revalidate the data and ensure the UI doesn't
      // remain in an incorrect state, ALWAYS trigger a
      // a refetch of the data, even on failure
      refetchQueriesOnFailure: true,
    }
github gempir / justlog / web / src / hooks / useAvailableLogs.ts View on Github external
export function useAvailableLogs(channel: string | null, username: string | null): [AvailableLogs, Error | undefined] {
    const { state, setState } = useContext(store);

    // @ts-ignore
    const { data } = useQuery<[AvailableLogs, Error | undefined]>(["availableLogs", { channel: channel, username: username }], () => {
        if (channel && username) {
            const channelIsId = isUserId(channel);
            const usernameIsId = isUserId(username);

            if (channelIsId) {
                channel = getUserId(channel)
            }
            if (usernameIsId) {
                username = getUserId(username)
            }

            const queryUrl = new URL(`${state.apiBaseUrl}/list`);
            queryUrl.searchParams.append(`channel${channelIsId ? "id" : ""}`, channel);
            queryUrl.searchParams.append(`user${usernameIsId ? "id" : ""}`, username);

            return fetch(queryUrl.toString()).then((response) => {
github tannerlinsley / react-query / examples / suspense / src / components / Projects.js View on Github external
export default function Projects({ setActiveProject }) {
  const { data, isFetching } = useQuery("projects", fetchProjects);

  return (
    <div>
      <h1>Projects {isFetching ? <Spinner /> : null}</h1>
      {data.map(project => (
        <p key={project.name}>
          <Button
            onClick={() => {
              // Prefetch the project query
              prefetchQuery(["project", { id: project.name }], fetchProject);
              setActiveProject(project.name);
            }}
          >
            Load
          </Button>{" "}
          {project.name}
github gempir / justlog / web / src / hooks / useFfzGlobalEmotes.ts View on Github external
export function useFfzGlobalEmotes(): Array<ThirdPartyEmote> {
	const { isLoading, error, data } = useQuery("ffz:global", () => {
		return fetch("https://api.frankerfacez.com/v1/set/global").then(res =>
			res.json() as Promise<FfzGlobalEmotesResponse>
		);
	}, QueryDefaults);

	if (isLoading || !data?.sets) {
		return [];
	}

	if (error) {
		console.error(error);
		return [];
	}

	const emotes = [];
github gempir / justlog / web / src / hooks / useFfzChannelEmotes.ts View on Github external
export function useFfzChannelEmotes(channelId: string): Array<ThirdPartyEmote> {
	const { isLoading, error, data } = useQuery(["ffz:channel", { channelId: channelId }], () => {
		if (channelId === "") {
			return Promise.resolve({sets: {}});
		}

		return fetch(`https://api.frankerfacez.com/v1/room/id/${channelId}`).then(res =>
			res.json() as Promise<FfzChannelEmotesResponse>
		);
	}, QueryDefaults);

	if (isLoading || !data?.sets) {
		return [];
	}

	if (error) {
		console.error(error);
		return [];
github tannerlinsley / react-query / examples / basic / pages / index.js View on Github external
export default () => {
  const { data, isLoading, isFetching } = useQuery('projects', () =>
    fetch('/api/data')
  )

  return (
    <div style={{ textAlign: 'center' }}>
      <h1>Trending Projects</h1>
      <div>
        {isLoading ? (
          'Loading...'
        ) : data ? (
          <>
            <div>
              {data.map(project => (
                <p key={project}>
                  <Link href="/[user]/[repo]" as={`/${project}`}>
                    <a>{project}</a>
github tannerlinsley / react-query / examples / load-more-pagination / pages / index.js View on Github external
export default () => {
  const {
    data,
    isLoading,
    isFetching,
    isFetchingMore,
    fetchMore,
    canFetchMore,
  } = useQuery(
    'projects',
    ({ nextId } = {}) => fetch('/api/projects?cursor=' + (nextId || 0)),
    {
      paginated: true,
      getCanFetchMore: lastPage => lastPage.nextId,
    }
  )

  const loadMore = async () => {
    try {
      const { nextId } = data[data.length - 1]

      await fetchMore({
        nextId,
      })
    } catch {}
github exercism / website / app / javascript / hooks / request-query.ts View on Github external
export function useRequestQuery<TResult = unknown, TError = unknown>(
  key: QueryKey,
  request: Request,
  isMountedRef: React.MutableRefObject<boolean>
): QueryResult<TResult, TError> {
  return useQuery<TResult, TError>(
    key,
    () => handleFetch(request, isMountedRef),
    {
      refetchOnWindowFocus: false,
      staleTime: 1000 * 30,
      ...camelizeKeys(request.options),
    }
  )
}
github tannerlinsley / react-query / examples / sandbox / src / index.app.js View on Github external
function Todos({ initialFilter = "", setEditingIndex }) {
  const [filter, setFilter] = React.useState(initialFilter);

  const {
    data,
    isLoading,
    isFetching,
    error,
    failureCount,
    refetch
  } = useQuery(["todos", { filter }], fetchTodos);

  return (
    <div>
      <div>
        <label>
          Filter:{" "}
          <input value={filter} onChange={e => setFilter(e.target.value)} />
        </label>
      </div>
      {isLoading ? (
        <span>Loading... (Attempt: {failureCount + 1})</span>
      ) : error ? (
        <span>
          Error!{" "}
          <button onClick={() => refetch({ disableThrow: true })}>Retry</button>
        </span>