---
# System prepended metadata

title: Fetching Resource On State Change
tags: [Simple Application]

---

# Fetching Resource On State Change

> * 如有錯誤處指正或任何建議，懇請留言，感謝!
> * 搭配 ChatGPT 進行翻譯，請小心服用
> * ▸ ... 為英文原文


:::spoiler ...
For this tutorial, we would like to fetch the list of repositories for a given GitHub organization. To aid you, we have added the `getRepositories()` function to the bottom of the file. Your task is to use the `getRepositories()` function to fetch the list of repositories whenever the user updates the `org` input.
:::
在本次的教學中，我們將從GitHub組織中獲取repositories的列表。
為了幫助你，我們家加入`getRepositories()`函式在檔案下方。你的任務是每當使用者在`org`輸入框中更新資料時，使用`getRepositories()`函式去獲取repositories的列表,。
:::spoiler ...
Qwik provides [`useResource$()`](https://qwik.builder.io/docs/components/resource/) and `<Resource>` to help you fetch and display data from the server. When fetching data the application can be in one of three states:
:::
Qwik提供[`useResource$()`](https://qwik.builder.io/docs/components/resource/)和`<Resource>`去幫助你從服務器去獲取和展示資料。
當獲取資料時，應用程式將屬於以下其中一種狀態：
:::spoiler ...
-   `pending`: the data is being fetched from the server => Render `loading...` indicator.
-   `resolved`: the data has successfully been fetched from the server => Render the data.
-   `rejected`: the data could not be fetched from the server due to an error => Render the error.
:::
- `pending`：當資料從服務器中被獲取 => 渲染`loading...`指示器。
- `resolved`：當資料成功的從服務器中被獲取=> 渲染資料。
- `rejected`：當資料因為錯誤而無法從服務器中獲取=> 渲染錯誤。

:::spoiler ...
Use [`useResource$()`](https://qwik.builder.io/docs/components/resource/) function to set up how the data is fetched from the server. Use `<Resource>` to display the data.
:::
使用[`useResource$()`](https://qwik.builder.io/docs/components/resource/)函式去建立資料是如何從服務器被獲取。使用`<Resource>`去展示資料。
:::spoiler ...

## Fetching data

Use [`useResource$()`](https://qwik.builder.io/docs/components/resource/) to set up how the data is fetched from the server.
:::
## 獲取資料
使用[`useResource$()`](https://qwik.builder.io/docs/components/resource/) 去建立建立資料是如何從服務器被獲取。

```jsx
  const reposResource = useResource$<string[]>(({ track, cleanup }) => {
    // We need a way to re-run fetching data whenever the `github.org` changes.
    // Use `track` to trigger re-running of this data fetching function.
    track(() => github.org);

    // A good practice is to use `AbortController` to abort the fetching of data if
    // new request comes in. We create a new `AbortController` and register a `cleanup`
    // function which is called when this function re-runs.
    const controller = new AbortController();
    cleanup(() => controller.abort());

    // Fetch the data and return the promises.
    return getRepositories(github.org, controller);
  });

```
:::spoiler ...
The [`useResource$()`](https://qwik.builder.io/docs/components/resource/) function returns a `ResourceReturn` object, which is a Promise-like object that can be serialized by Qwik. The [`useResource$()`](https://qwik.builder.io/docs/components/resource/) function allows you to `track` store properties so that the [`useResource$()`](https://qwik.builder.io/docs/components/resource/) function can be reactive on store changes. The `cleanup` function allows you to register a code that needs to be run to release resources from the previous run. Finally, the [`useResource$()`](https://qwik.builder.io/docs/components/resource/) function returns a promise that will resolve to the value.
:::
[`useResource$()`](https://qwik.builder.io/docs/components/resource/)函式回傳一個`ResourceReturn`物件，該物件是一個類似於promise的物件能夠被Qwik序列化。
[`useResource$()`](https://qwik.builder.io/docs/components/resource/)函式允許你去`track` store屬性，因此[`useResource$()`](https://qwik.builder.io/docs/components/resource/)函式能夠對store更改時做出反應。
`cleanup`函式允許你註冊一段程式去需要被執行，以釋放先前執行的資源。
最後[`useResource$()`](https://qwik.builder.io/docs/components/resource/)函式回傳一個解析為值的promise。
:::spoiler ...

## Rendering data

Use `<Resource>` to display the data of [`useResource$()`](https://qwik.builder.io/docs/components/resource/) function. The `<Resource>` allows you to render different content depending if the resource is `pending`, `resolved` or `rejected`.

On the server the `<Resource>` does not render `loading` state, instead, it pauses rendering until the resource is resolved and will always render as either `resolved` or `rejected`. (On the client, the `<Resource>` renders all states including `pending`.)
:::
## 渲染資料
使用`<Resource>`展示[`useResource$()`](https://qwik.builder.io/docs/components/resource/)函式的資料。
`<Resource>`允許你根據資料是否處於`pending`、`resolved`或是`rejected`狀態渲染不同的內容。（在客戶端，`<Resource>`渲染所有的狀態，包含`pending`)

```jsx
<Resource
  value={resourceToRender}
  onPending={() => <div>Loading...</div>}
  onRejected={(reason) => <div>Error: {reason}</div>}
  onResolved={(data) => <div>{data}</div>}
/>

```
:::spoiler ...
## SSR vs Client

Notice that the same code can render on both server and client (with slightly different behavior, which skips the `pending` state rendering on the server.)

::: 
## SSR vs Client
注意：相同的程式可以渲染在服務器和客戶端（略有不同的是，服務器不會渲染`pending`狀態）


###### tags: `Simple Application`