當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript react-relay.commitMutation函數代碼示例

本文整理匯總了TypeScript中react-relay.commitMutation函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript commitMutation函數的具體用法?TypeScript commitMutation怎麽用?TypeScript commitMutation使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了commitMutation函數的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: commit

function commit(
  environment: Environment,
  todos: TodoListFooter_viewer["todos"],
  user: TodoListFooter_viewer,
) {
  return commitMutation(
    environment,
    {
      mutation,
      variables: {
        input: {},
      },
      updater: (store) => {
        const payload = store.getRootField('removeCompletedTodos')!;
        sharedUpdater(store, user, payload.getValue('deletedTodoIds'));
      },
      optimisticUpdater: (store) => {
        if (todos && todos.edges) {
          const deletedIDs = todos.edges
            .filter(edge => edge!.node!.complete)
            .map(edge => edge!.node!.id);
          sharedUpdater(store, user, deletedIDs);
        }
      },
    }
  );
}
開發者ID:vvakame,項目名稱:til,代碼行數:27,代碼來源:RemoveCompletedTodosMutation.ts

示例2: updateConversation

export function updateConversation(
  environment: Environment,
  conversation: Conversation,
  fromLastViewedMessageId: string,
  onCompleted: MutationConfig<any>["onCompleted"],
  onError: MutationConfig<any>["onError"]
) {
  return commitMutation<UpdateConversationMutation>(environment, {
    updater: store => {
      store.get(conversation.__id).setValue(false, "unread")
    },
    onCompleted,
    onError,
    mutation: graphql`
      mutation UpdateConversationMutation($input: UpdateConversationMutationInput!) {
        updateConversation(input: $input) {
          conversation {
            id
            from_last_viewed_message_id
          }
        }
      }
    `,
    variables: {
      input: {
        conversationId: conversation.id,
        fromLastViewedMessageId,
      },
    },
  })
}
開發者ID:artsy,項目名稱:emission,代碼行數:31,代碼來源:UpdateConversation.ts

示例3: commit

function commit(
  environment: Environment,
  text: string,
  todo: Todo_todo,
) {
  return commitMutation(
    environment,
    {
      mutation,
      variables: {
        input: {text, id: todo.id},
      },
      optimisticResponse: getOptimisticResponse(text, todo),
    }
  );
}
開發者ID:vvakame,項目名稱:til,代碼行數:16,代碼來源:RenameTodoMutation.ts

示例4: commit

function commit(
  environment: Environment,
  complete: boolean,
  todo: Todo_todo,
  user: Todo_viewer,
) {
  return commitMutation(
    environment,
    {
      mutation,
      variables: {
        input: {complete, id: todo.id},
      },
      optimisticResponse: getOptimisticResponse(complete, todo, user),
    }
  );
}
開發者ID:vvakame,項目名稱:til,代碼行數:17,代碼來源:ChangeTodoStatusMutation.ts

示例5: commit

function commit(
  environment: Environment,
  complete: boolean,
  todos: TodoList_viewer["todos"],
  user: TodoList_viewer,
) {
  return commitMutation(
    environment,
    {
      mutation,
      variables: {
        input: {complete},
      },
      optimisticResponse: getOptimisticResponse(complete, todos, user),
    }
  );
}
開發者ID:vvakame,項目名稱:til,代碼行數:17,代碼來源:MarkAllTodosMutation.ts

示例6: commit

function commit(
  environment: Environment,
  text: string,
  user: TodoApp_viewer,
) {
  return commitMutation(
    environment,
    {
      mutation,
      variables: {
        input: {
          text,
          clientMutationId: tempID++,
        },
      },
      updater: (store) => {
        const payload = store.getRootField('addTodo')!;
        const newEdge = payload.getLinkedRecord('todoEdge');
        sharedUpdater(store, user, newEdge);
      },
      optimisticUpdater: (store) => {
        const id = 'client:newTodo:' + tempID++;
        const node = store.create(id, 'Todo');
        node.setValue(text, 'text');
        node.setValue(id, 'id');
        const newEdge = store.create(
          'client:newEdge:' + tempID++,
          'TodoEdge',
        );
        newEdge.setLinkedRecord(node, 'node');
        sharedUpdater(store, user, newEdge);
        const userProxy = store.get(user.id)!;
        userProxy.setValue(
          userProxy.getValue('totalCount') + 1,
          'totalCount',
        );
      },
    }
  );
}
開發者ID:vvakame,項目名稱:til,代碼行數:40,代碼來源:AddTodoMutation.ts

示例7: commit

function commit(
  environment: Environment,
  todo: Todo_todo,
  user: Todo_viewer,
) {
  return commitMutation(
    environment,
    {
      mutation,
      variables: {
        input: {id: todo.id},
      },
      updater: (store) => {
        const payload = store.getRootField('removeTodo')!;
        sharedUpdater(store, user, payload.getValue('deletedTodoId'));
      },
      optimisticUpdater: (store) => {
        sharedUpdater(store, user, todo.id);
      },
    }
  );
}
開發者ID:vvakame,項目名稱:til,代碼行數:22,代碼來源:RemoveTodoMutation.ts

示例8: setErrors

  const commit: Commit<M> = (commitOptions = {}) => {
    if (pending) return;

    const input = {
      ...state,
      ...commitOptions.merge,
    };
    if (commitOptions.merge != null) setState(input);

    // Find, set, and forus the first error only.
    // Sure we can set all errors at once, but I prefer less noisy UI.
    // The order is defined by object property order which is reliable:
    // https://stackoverflow.com/a/23202095/233902
    // Why not an array? Object is more handy for GraphQL.
    // Check api/schema.graphql SignInErrors type.
    const handleErrors = (errors: Errors<M>): { hasError: boolean } => {
      const error = Object.entries(errors).find(([, value]) => value != null);
      if (error != null && error[1] != null) {
        // @ts-ignore PR anyone?
        setErrors({ [error[0]]: error[1] });
        const field = focusablesRef.current[error[0]];
        if (field) field.focus();
      } else {
        setErrors({});
      }
      return { hasError: error != null };
    };

    if (useMutationOptions.validator) {
      const errors = useMutationOptions.validator(input);
      if (handleErrors(errors).hasError) return;
    }

    setPending(true);

    if (disposableRef.current) disposableRef.current.dispose();

    disposableRef.current = commitMutation<M>(relayEnvironment, {
      mutation,
      variables: { input },
      onCompleted(response, payloadErrors) {
        setPending(false);
        if (payloadErrors) {
          handleApiGraphQLError(payloadErrors, {
            401() {
              appHref.replace({
                pathname: '/signin',
                query: { redirectUrl: Router.asPath || '' },
              });
            },
            403() {
              // eslint-disable-next-line no-alert
              alert(intl.formatMessage(messages.forbidden));
            },
            404() {
              // This should not happen with mutation.
              // eslint-disable-next-line no-alert
              alert(intl.formatMessage(messages.notFound));
            },
            unknown() {
              // eslint-disable-next-line no-alert
              alert(payloadErrors);
            },
          });
          return;
        }
        const firstResponse = response[Object.keys(response)[0]] as Response<M>;
        const errors = ((firstResponse && firstResponse.errors) ||
          {}) as Errors<M>;
        if (handleErrors(errors).hasError) return;
        if (commitOptions.onSuccess) {
          commitOptions.onSuccess(firstResponse);
        }
      },
      onError(error) {
        setPending(false);
        if (error == null) return;
        const isNetworkError = error.message === 'Failed to fetch';
        const message = isNetworkError
          ? intl.formatMessage(messages.noInternetAccess)
          : error.message;
        // eslint-disable-next-line no-alert
        alert(message);
      },
    });
  };
開發者ID:este,項目名稱:este,代碼行數:86,代碼來源:useMutation.ts

示例9: sendConversationMessage

export function sendConversationMessage(
  environment: Environment,
  conversation: Conversation,
  text: string,
  onCompleted: MutationConfig<any>["onCompleted"],
  onError: MutationConfig<any>["onError"]
) {
  const storeUpdater = (store: RecordSourceSelectorProxy) => {
    const mutationPayload = store.getRootField("sendConversationMessage")
    const newMessageEdge = mutationPayload.getLinkedRecord("messageEdge")
    const conversationStore = store.get(conversation.__id)
    const connection = ConnectionHandler.getConnection(conversationStore, "Messages_messages")
    ConnectionHandler.insertEdgeBefore(connection, newMessageEdge)
  }
  return commitMutation<SendConversationMessageMutation>(environment, {
    onCompleted,
    onError,
    optimisticUpdater: storeUpdater,
    updater: storeUpdater,

    // TODO: See if we can extract the field selections into a fragment and share it with the normal pagination fragment.
    //      Also looks like we can get rid of the `body` selection.
    mutation: graphql`
      mutation SendConversationMessageMutation($input: SendConversationMessageMutationInput!) {
        sendConversationMessage(input: $input) {
          messageEdge {
            node {
              impulse_id
              is_from_user
              body
              __id
              ...Message_message
            }
          }
        }
      }
    `,

    variables: {
      input: {
        id: conversation.id,
        from: conversation.from.email,
        body_text: text,
        // Reply to the last message
        reply_to_message_id: conversation.last_message_id,
      },
    },

    // TODO: Figure out which of these keys is *actually* required for Relay Modern and update the typings to reflect that.
    //      And if it’s really true that this config isn’t enough to update the connection and we really need the updater
    //      functions.
    configs: [
      {
        type: "RANGE_ADD",
        parentName: "conversation",
        parentID: "__id",
        connectionName: "messages",
        edgeName: "messageEdge",
        rangeBehaviors: {
          "": "APPEND",
        },
        connectionInfo: [
          {
            key: "Messages_messages",
            rangeBehavior: "append",
          },
        ],
      },
    ],

    optimisticResponse: {
      sendConversationMessage: {
        messageEdge: {
          node: {
            body: text,
            from: {
              email: conversation.from.email,
              name: null,
            },
            is_from_user: true,
            created_at: null, // Intentionally left blank so Message can recognize this as an optimistic response.
            attachments: [],
          } as any,
        },
      },
    },
  })
}
開發者ID:artsy,項目名稱:emission,代碼行數:88,代碼來源:SendConversationMessage.ts


注:本文中的react-relay.commitMutation函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。