> For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt.

# 数据获取

无论是从远程服务器获取静态内容，还是与 REST API 进行数据交互，ReactLynx 应用通常需要通过网路请求从外部数据源获取信息。例如，你可能希望在社交应用中加载用户的动态，或是在电商应用中获取最新的商品列表。

Lynx 提供了 [Fetch API](/next/zh/api/lynx-api/global/fetch.md)，使你能够进行网络请求，你可以参考[网络](/next/zh/guide/interaction/networking.md)章节了解更多信息。Lynx 提供的 Fetch API 可以与 React 社区生态中的服务器状态管理（Server State Management）库结合使用，如 [Tanstack Query（React Query）](https://tanstack.com/query)等，以简化数据获取和状态管理。

需要注意的是，Lynx 的 Fetch API 与 [Web Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) 存在细微差异，你可以参考 [Fetch API Reference - 兼容性](/next/zh/api/lynx-api/global/fetch.md#兼容性)章节来了解这些差异。因此，你可能需要对 React 社区中的库进行适配，以确保其兼容性。如果你遇到问题，欢迎提出功能请求，或[贡献](https://github.com/lynx-family/lynx/blob/develop/CONTRIBUTING.md)新的功能来帮助 Lynx 更好地支持 React 社区生态。

## 使用 TanStack Query

TanStack Query 是 React 生态中流行的服务器状态管理库，能够帮助开发者轻松管理数据获取和缓存。

### 安装依赖


```sh [npm]
npm install @tanstack/react-query
```

```sh [yarn]
yarn add @tanstack/react-query
```

```sh [pnpm]
pnpm add @tanstack/react-query
```

```sh [bun]
bun add @tanstack/react-query
```

```sh [deno]
deno add npm:@tanstack/react-query
```

### 示例

以下示例应用演示了如何在 ReactLynx 中使用 TanStack Query 结合 Fetch API 来获取、显示，并删除 [JSONPlaceholder API](https://jsonplaceholder.typicode.com/) 的用户帖子。

应用首先通过 Tanstack Query 提供的 [`useQuery`](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) hook 调用 `fetchPosts` 获取并展示前 10 个帖子。当用户点击“Delete Post 1”按钮后，通过 [`useMutation`](https://tanstack.com/query/latest/docs/framework/react/reference/useMutation) hook 立即进行[乐观更新（Optimistic Update）](https://tanstack.com/query/v4/docs/framework/react/guides/optimistic-updates)：将 `id` 为 `1` 的帖子从列表中移除，同时使用 `deletePost` 调用 Fetch API 发送删除请求，如若请求失败则会回滚至原状态。

**下面是一个示例: networking**

**Entry:** `src/react-query`
**Bundle:** `dist/react-query.lynx.bundle`

```tsx
import { root } from "@lynx-js/react";
import { QueryClient, QueryClientProvider, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import "./index.scss";

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

const queryClient = new QueryClient();

const fetchPosts = async (): Promise<Post[]> => {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts");
  if (!response.ok) {
    throw new Error("Failed to fetch posts");
  }
  const data = await response.json();
  return data.slice(0, 10); // Only show the first 10 posts
};

const deletePost = async (postId: number) => {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${postId}`,
    {
      method: "DELETE",
    },
  );
  if (!response.ok) {
    throw new Error("Failed to delete post");
  }
  return postId;
};

const App = () => {
  const queryClient = useQueryClient();

  // Fetch posts
  const {
    data: posts,
    isLoading,
    isError,
    error,
  } = useQuery({
    queryKey: ["posts"],
    queryFn: fetchPosts,
  });

  // Mutation to delete post optimistically
  const mutation = useMutation({
    mutationFn: () => deletePost(1),
    onMutate: async () => {
      await queryClient.cancelQueries({ queryKey: ["posts"] });

      // Snapshot current state
      const previousPosts = queryClient.getQueryData<Post[]>(["posts"]);

      // Optimistically remove post with ID 1
      queryClient.setQueryData(["posts"], (oldPosts: Post[] | undefined) => {
        return oldPosts ? oldPosts.filter((post) => post.id !== 1) : [];
      });

      // Return previous state to OnError for rolling back optimistic update
      return { previousPosts };
    },
    onError: (err, variables, context) => {
      // Rollback to previous state
      if (context?.previousPosts) {
        queryClient.setQueryData(["posts"], context.previousPosts);
      }
    },
  });

  const deleteFirstPost = () => {
    "background only";
    mutation.mutate();
  };

  return (
    <view className="container">
      {isLoading ? <text className="container__loading">Loading...</text> : isError
        ? (
          <text className="container__error">
            {error?.message || "Error fetching posts"}
          </text>
        )
        : (
          posts?.map((post) => (
            <view key={post.id} className="container__post">
              <text className="container__post-text">{`${post.id} : ${post.title}`}</text>
            </view>
          ))
        )}

      {/* Button to trigger mutation */}
      <view bindtap={deleteFirstPost} className="container__button">
        <text className="container__button-text">Delete Post 1</text>
      </view>
    </view>
  );
};

root.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
);

if (import.meta.webpackHot) {
  import.meta.webpackHot.accept();
}

```

v0.5.0


