How to use react-query - 10 common examples

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 exercism / website / test / javascript / setupTests.js View on Github external
afterEach(async () => {
  queryCache.cancelQueries()
  queryCache.clear()

  // waitFor is important here. If there are queries that are being fetched at
  // the end of the test and we continue on to the next test before waiting for
  // them to finalize, the tests can impact each other in strange ways.
  await waitFor(() => expect(queryCache.isFetching).toBe(0))

  await flushPromises()
  await act(async () => await null)
})
github exercism / website / test / javascript / setupTests.js View on Github external
afterEach(async () => {
  queryCache.cancelQueries()
  queryCache.clear()

  // waitFor is important here. If there are queries that are being fetched at
  // the end of the test and we continue on to the next test before waiting for
  // them to finalize, the tests can impact each other in strange ways.
  await waitFor(() => expect(queryCache.isFetching).toBe(0))

  await flushPromises()
  await act(async () => await null)
})
github tannerlinsley / react-query / examples / optimistic-updates / pages / index.js View on Github external
async function handleSubmit(event) {
    event.preventDefault()
    // mutate current data to optimistically update the UI
    // the fetch below could fail, so we need to revalidate
    // regardless

    setQueryData('todos', [...data, text], {
      shouldRefetch: false,
    })

    try {
      // send text to the API
      await mutatePostTodo(text)
      setText('')
    } catch (err) {
      console.error(err)
    }
  }
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 Mines-Paristech-Students / Portail-des-eleves / frontend / src / components / associations / library / management / loans / LoansTable.tsx View on Github external
loanableId,
  apiParameters,
}: {
  loanableId: string;
  apiParameters?: Partial<ListLoansApiParameters>;
}) => {
  const { sendInfoToast, sendSuccessToast, sendErrorToast } = useContext(
    ToastContext
  );

  // The loan edited in the modal.
  const [editLoan, setEditLoan] = useState<Loan | null>(null);

  const { columns, sorting } = useColumns(columnsDefinition(setEditLoan));

  const [edit] = useMutation(api.loans.patch, {
    onMutate: () => sendInfoToast("Modification en cours…"),
    onSuccess: () => {
      sendSuccessToast("Modifications enregistrées !");
      queryCache.invalidateQueries("loans.list");
      setEditLoan(null);
    },
    onError: () => sendErrorToast("Une erreur est survenue."),
  });

  // Submit the form in the modal.
  const submit = (values, { setSubmitting }) => {
    if (editLoan) {
      if (values.status !== "RETURNED") {
        // `realReturnDate` may only change when the loanable returns.
        values.realReturnDate = null;
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 tannerlinsley / react-query / examples / suspense / src / components / Projects.js View on Github external
onClick={() => {
              // Prefetch the project query
              prefetchQuery(["project", { id: project.name }], fetchProject);
              setActiveProject(project.name);
            }}
          >
github exercism / website / app / javascript / components / mentoring / testimonials-list / UnrevealedTestimonial.tsx View on Github external
const updateCache = useCallback(() => {
    const oldData = queryCache.getQueryData<PaginatedResult>(cacheKey)

    if (!oldData || !revealedTestimonial) {
      return
    }

    queryCache.setQueryData(cacheKey, {
      ...oldData,
      results: oldData.results.map((oldTestimonial) => {
        return oldTestimonial.id === revealedTestimonial.id
          ? revealedTestimonial
          : oldTestimonial
      }),
    })
  }, [cacheKey, revealedTestimonial])