urql簡介
urql是一個快速,輕巧且可自定義的GraphQL客戶端。是一個js的庫。
安裝urql
# npm
npm i --save urql graphql
# or yarn
yarn add urql graphql
使用urql
- 從服務器 GraphQL Endpoint 來生成客戶端
import { createClient, Provider } from 'urql';
const client = createClient({
url: 'https://0ufyz.sse.codesandbox.io' ,
fetchOptions: () => {
const token = getToken();
return {
headers: { authorization: token ? `Bearer ${token}` : '' }
};
}
});
const App = () => (
<Provider value={client}>
<Todos />
</Provider>
);
通過createClient創建一個客戶端,url指定服務端地址,fetchOptions提供一個函數,返回要添加到請求中的參數信息,比如token
利用react的上下文來傳遞客戶端給子組件,則接下來在Todos組件中可以直接使用query而不需要再次創建客戶端
- 執行查詢
import { useQuery } from 'urql';
const TodosQuery = `
query ($id : ID!) {
todos {
id
title
}
}
`;
const Todos = () => {
const [result, reexecuteQuery] = useQuery({
query: TodosQuery,
variables: {"id" : '1111' }
});
const { data, fetching, error } = result;
if (fetching) return <p>Loading...</p>;
if (error) return <p>Oh no... {error.message}</p>;
return (
<ul>
{data.todos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
};
通過useQuery這個Hook函數,即刻進行查詢返回結果,其中query參數代表請求的GraphQL語句,variables參數代表傳遞的變量數據。
返回值是數組,第一個值是結果,結果包含data,fetching,erro桑屬性,分別代表數據結果,執行未完成和出錯信息。
- 執行變更
與查詢不一樣的是,變更語句不會在調用useMutation這個Hook函數時立即執行,而是需要通過函數返回值的第二個元素(其是一個函數),傳入數據調用以後纔會請求執行。
import { useMutation} from 'urql';
const UpdateTodo = `
mutation ($id: ID!, $title: String!) {
updateTodo (id: $id, title: $title) {
id
title
}
}
`;
const Todo = ({ id, title }) => {
const [updateTodoResult, updateTodo] = useMutation(UpdateTodo);
const submit = newTitle => {
const variables = { id, title: newTitle || '' };
updateTodo(variables).then(result => {
// The result is almost identical to `updateTodoResult` with the exception
// of `result.fetching` not being set.
});
};
};