跳至主要內容

graphQLSelectorFamily()

graphQLSelectorFamily() 類似於 graphQLSelector(),只不過它會回傳一個函式,而該函式會接受參數並回傳該參數的選擇器。這基本上讓我們能夠將參數從呼叫元件傳遞給查詢,其依據是 props 或其他狀態。


function graphQLSelectorFamily<
TVariables: Variables,
TData: $ReadOnly<{[string]: mixed}>,
P: Parameter = TVariables,
T = TData,
TRawResponse = void,
TMutationVariables: Variables = {},
TMutationData: $ReadOnly<{[string]: mixed}> = {},
TMutationRawResponse = void,
>({
key: string,

environment: IEnvironment | EnvironmentKey,

query:
| Query<TVariables, TData, TRawResponse>
| GraphQLSubscription<TVariables, TData, TRawResponse>,

variables:
| TVariables
| P => TVariables | null
| P => ({get: GetRecoilValue}) => TVariables | null,

mapReponse:
| (TData, {get: GetRecoilValue, variables: TVariables}) => T
| (TData, {get: GetRecoilValue, variables: TVariables}) => P => T,

default?:
| T
| P => T,

mutations?: {
mutation: Mutation<TMutationVariables, TMudationData, TMutationRawResposne>,
variables:
| T => TMutationVariables | null
| T => P => TMutationVariables | null,
},

}): P => RecoilState<T>
  • key - 用於識別選擇器的唯一字串。
  • environment - Relay 環境,或用來與 <RecoilRelayEnvironment> 周遭提供的環境相符的 EnvironmentKey
  • query - GraphQL 查詢或訂閱。查詢中支援 片段
  • variables - 提供要對查詢使用之 變數 物件的回呼。它可能是變數物件本體,或提供 family 參數並回傳變數的回呼。也可以使用內層回呼,以取得一個 get() 函式,讓選擇器能夠參照其他上游 Recoil 原子/選擇器。如果將 null 提供為變數,則不會執行查詢,而是會使用 default 值。
  • mapResponse - 將 GraphQL 結果轉換為用於選擇器值之 callback。它也提供 get() 函數,因此它可以參考其他 Recoil 原子或選擇器來執行轉換。也可以使用接收 family 參數的巢狀 callback。
  • 預設 - 如果將 null 提供為 variables,則使用預設值。可以使用一個獲取 family 參數作為參數的 callback。如果未提供 預設,則選擇器將保持在擱置狀態。
  • mutations - Graph QL 突變 和變數的選用設定,如果選擇器顯式寫入,則提交。

具參數查詢

const eventQuery = graphQLSelectorFamily({
key: 'EventQuery',
environment: myEnvironment,
query: graphql`
query MyEventQuery($id: ID!) {
myevent(id: $id) {
id
name
}
}
`,
variables: id => ({id}),
mapResponse: data => data.myevent,
});
function MyComponent(props) {
const eventInfo = useRecoilValue(eventQuery(props.eventID));

return (
<div>
<h1>{eventInfo.name}</h1>
</div>
);
}

具參數及上游狀態查詢

variablesmapResponse 皆可以依賴參數及其他上游 Recoil 原子或選擇器。

const eventQuery = graphQLSelectorFamily({
key: 'EventQuery',
environment: myEnvironment,
query: graphql`
query MyEventQuery($id: ID!) {
myevent(id: $id) {
id
name
}
}
`,
variables: id => ({get}) => ({id, clientID: get(clientIDAtom)}),
mapResponse: (data, {get}) => id => ({
id,
name: data.myevent?.name,
region: get(regionForIDSelector(id)),
}),
});