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 ?  : null}</h1>
      {data.map(project =&gt; (
        <p>
          <button> {
              // Prefetch the project query
              prefetchQuery(["project", { id: project.name }], fetchProject);
              setActiveProject(project.name);
            }}
          &gt;
            Load
          </button>{" "}
          {project.name}</p></div>
github gempir / justlog / web / src / hooks / useFfzGlobalEmotes.ts View on Github external
export function useFfzGlobalEmotes(): Array {
	const { isLoading, error, data } = useQuery("ffz:global", () =&gt; {
		return fetch("https://api.frankerfacez.com/v1/set/global").then(res =&gt;
			res.json() as Promise
		);
	}, 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 {
	const { isLoading, error, data } = useQuery(["ffz:channel", { channelId: channelId }], () =&gt; {
		if (channelId === "") {
			return Promise.resolve({sets: {}});
		}

		return fetch(`https://api.frankerfacez.com/v1/room/id/${channelId}`).then(res =&gt;
			res.json() as Promise
		);
	}, 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 () =&gt; {
  const { data, isLoading, isFetching } = useQuery('projects', () =&gt;
    fetch('/api/data')
  )

  return (
    <div style="{{">
      <h1>Trending Projects</h1>
      <div>
        {isLoading ? (
          'Loading...'
        ) : data ? (
          &lt;&gt;
            <div>
              {data.map(project =&gt; (
                <p>
                  
                    <a>{project}</a></p></div></div></div>
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(
  key: QueryKey,
  request: Request,
  isMountedRef: React.MutableRefObject
): QueryResult {
  return useQuery(
    key,
    () =&gt; 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}"> setFilter(e.target.value)} /&gt;
        </label>
      </div>
      {isLoading ? (
        <span>Loading... (Attempt: {failureCount + 1})</span>
      ) : error ? (
        <span>
          Error!{" "}
          <button> refetch({ disableThrow: true })}&gt;Retry</button>
        </span></div>