How to use @apollo/react-hooks - 10 common examples

To help you get started, we’ve selected a few @apollo/react-hooks examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ian13456 / mine.js / src / components / Forms / LoginForm / LoginForm.js View on Github external
const LoginForm = ({ history, loading: authLoading }) => {
  const client = useApolloClient()

  const [login, { error, loading }] = useMutation(LOGIN_MUTATION, {
    onCompleted: data => {
      setCookie(data.login.token)

      // Force a reload of all current queries now that user is
      // logged in
      client.cache.reset().then(() => {
        history.push('/home')
      })
    },
    onError: err => console.error(err)
  })

  if (loading || authLoading) {
    return 
  }
github ian13456 / mine.js / src / components / Forms / LoginForm / LoginForm.js View on Github external
const LoginForm = ({ history, loading: authLoading }) => {
  const client = useApolloClient()

  const [login, { error, loading }] = useMutation(LOGIN_MUTATION, {
    onCompleted: data => {
      setCookie(data.login.token)

      // Force a reload of all current queries now that user is
      // logged in
      client.cache.reset().then(() => {
        history.push('/home')
      })
    },
    onError: err => console.error(err)
  })

  if (loading || authLoading) {
    return
github SolidZORO / leaa / packages / leaa-dashboard / src / pages / Coupon / EditCoupon / EditCoupon.tsx View on Github external
export default (props: IPage) => {
  const { t } = useTranslation();
  const { id } = props.match.params as { id: string };

  // ref
  const infoFormRef = useRef>(null);

  // query
  const getCouponVariables = { id: Number(id) };
  const getCouponQuery = useQuery<{ coupon: Coupon }, CouponArgs>(GET_COUPON, {
    variables: getCouponVariables,
    fetchPolicy: 'network-only',
  });

  // mutation
  const [submitVariables, setSubmitVariables] = useState<{ id: number; coupon: UpdateCouponInput }>();
  const [updateCouponMutate, updateCouponMutation] = useMutation(UPDATE_COUPON, {
    variables: submitVariables,
    // apollo-link-error onError: e => messageUtil.gqlError(e.message),
    onCompleted: () => messageUtil.gqlSuccess(t('_lang:updatedSuccessfully')),
    refetchQueries: () => [{ query: GET_COUPON, variables: getCouponVariables }],
  });

  const onSubmit = async () => {
    const infoData: ISubmitData = await infoFormRef.current?.onValidateForm();
github VulcanJS / Vulcan / packages / vulcan-core / lib / modules / containers / delete2.js View on Github external
export const useDelete2 = (options) => {
  const { collectionName, collection } = extractCollectionInfo(options);
  const { fragmentName, fragment } = extractFragmentInfo(options, collectionName);
  const typeName = collection.options.typeName;
  const {
    //input: optionsInput,
    //_id: optionsId,
    mutationOptions = {},
  } = options;

  const query = buildDeleteQuery({
    fragment,
    fragmentName, typeName
  });

  const [deleteFunc, ...rest] = useMutation(query, {
    // optimistic update
    update: multiQueryUpdater({ collection, typeName, fragment, fragmentName }),
    ...mutationOptions
  });
  const extendedDeleteFunc = (args/*{ input: argsInput, _id: argsId }*/) => {
    return deleteFunc({
      variables: {
        ...computeQueryVariables(options, args)
      }
    });
  };
  return [extendedDeleteFunc, ...rest];
};
github karanpratapsingh / Proximity / app / screens / NotificationScreen / components / NotificationCard.tsx View on Github external
const NotificationCard: React.FC = ({ notificationId, avatar, resourceId, handle, type, time }) => {

  const { theme } = useContext(AppContext);
  const { navigate } = useNavigation();
  const notificationText = NotificationText[type];
  const { readableTime } = parseTimeElapsed(time);

  const [deleteNotification, { loading: deleteNotificationLoading, called: deleteNotificationCalled }] = useMutation(MUTATION_DELETE_NOTIFICATION);

  const swipeableRef = useRef();

  const navigateAction = () => {
    if (resourceId === '') return;

    if (type === NotificationType.FOLLOW) {
      navigate(Routes.ProfileViewScreen, { userId: resourceId });
    } else if (type === NotificationType.LIKE || type === NotificationType.COMMENT) {
      navigate(Routes.PostViewScreen, { postId: resourceId });
    }
  };

  const onDelete = () => {
    if (!deleteNotificationLoading && !deleteNotificationCalled) {
      // @ts-ignore
github tlambert03 / FPbase / static / src / fpbase-spectra / useCachedQuery.jsx View on Github external
const useCachedQuery = (query, cacheKey, maxAge) => {
  // fetch data no more than once every maxAge
  const [stash, setStash] = useState(getStorageWithExpire(cacheKey, maxAge))
  const client = useApolloClient()
  useEffect(() => {
    async function fetchData() {
      const { data } = await client.query({ query })
      if (data) {
        setStash(data)
        setStorageWithTimeStamp(cacheKey, data)
      }
    }
    if (!stash) fetchData()
  }, []) // eslint-disable-line
  return stash
}
github kyma-project / console / add-ons / src / services / Subscriptions.service.ts View on Github external
const onDelete = (item: Configuration) => {
    successNotification({
      title: NOTIFICATION.DELETE_CONFIGURATION.TITLE,
      content: NOTIFICATION.DELETE_CONFIGURATION.CONTENT.replace(
        CONFIGURATION_VARIABLE,
        item.name,
      ),
    });
    setOriginalConfigs(configs => configs.filter(c => c.name !== item.name));
  };

  const subscription = currentNamespace
    ? ADDONS_CONFIGURATION_EVENT_SUBSCRIPTION
    : CLUSTER_ADDONS_CONFIGURATION_EVENT_SUBSCRIPTION;

  useSubscription<
    SubscriptionPayload,
    AddonsConfigurationSubscriptionVariables
  >(subscription, {
    variables: {
      namespace: currentNamespace,
    },
    onSubscriptionData: ({ subscriptionData }) => {
      const { data, error } = subscriptionData;

      if (error) {
        // errorNotification('Error', ERRORS.SERVER);
        errorNotification({
          title: 'Error',
          content: '',
        });
        return;
github Thorium-Sim / thorium / src / components / views / PowerDistribution / index.js View on Github external
const PowerDistribution = ({client, simulator, clientObj}) => {
  const {loading, data} = useQuery(SYSTEMS_QUERY, {
    variables: {
      simulatorId: simulator.id,
    },
  });
  const {data: reactorSub} = useSubscription(REACTOR_SUB, {
    variables: {simulatorId: simulator.id},
  });
  const {data: systemsSub} = useSubscription(SYSTEMS_SUB, {
    variables: {simulatorId: simulator.id},
  });

  if (loading || !data) return null;
  const systems = systemsSub ? systemsSub.systemsUpdate : data.systems;
  const reactors = reactorSub ? reactorSub.reactorUpdate : data.reactors;
  // Get the batteries, get just the first one.
  const battery = reactors.find(r => r.model === "battery");
  const reactor = reactors.find(r => r.model === "reactor");
  const charge = battery && battery.batteryChargeLevel;

  const trainingSteps = hasBattery =>
    [
      {
        selector: ".nothing",
        content:
github hasura / learn-graphql / tutorials / frontend / typescript-react-apollo / app-final / src / components / Todo / TodoPublicList.tsx View on Github external
const TodoPublicListSubscription = () => {
  // Run a subscription to get the latest public todo
  const NOTIFY_NEW_PUBLIC_TODOS = gql`
    subscription notifyNewPublicTodos {
      todos(
        where: { is_public: { _eq: true } }
        limit: 1
        order_by: { created_at: desc }
      ) {
        id
        created_at
      }
    }
  `;

  const { loading, error, data } = useSubscription(NOTIFY_NEW_PUBLIC_TODOS);
  if (loading) {
    return <span>Loading...</span>;
  }
  if (error || !data) {
    return <span>Error</span>;
  }
  return (
    
  );
};
github dotansimha / graphql-code-generator / dev-test / githunt / types.reactApollo.hooks.tsx View on Github external
export function useOnCommentAddedSubscription(baseOptions?: ApolloReactHooks.SubscriptionHookOptions) {
  return ApolloReactHooks.useSubscription(OnCommentAddedDocument, baseOptions);
}
export type OnCommentAddedSubscriptionHookResult = ReturnType;