使用`react-apollo-hooks`和`useSubscription`钩子

时间:2019-04-25 11:27:56

标签: reactjs react-apollo react-hooks absinthe

我正在使用React,Apollo和react-apollo-hooks创建一个简单的待办事项应用程序以支持钩子,但是useSubscription钩子不会触发。

我知道实际的后端工作原理,因为我已经设置了graphiql应用程序,并且每当保存一个待办事项时,todoCreated事件就会在graphiql中显示。我也知道websocket的设置工作正常,因为查询和变异正在通过websocket。顺便说一下,我将Elixir,Phoenix和Absinthe用于后端。

这是Todo-app组件:

import React, { useState } from 'react';
import gql from 'graphql-tag';
import { useQuery, useMutation, useSubscription } from 'react-apollo-hooks';

import styles from 'styles.css';

const TODO_FRAGMENT = gql`
  fragment TodoFields on Todo {
    id
    description
  }
`;

const GET_TODOS = gql`
  {
    todos {
      ...TodoFields
    }
  }
  ${TODO_FRAGMENT}
`;

const SAVE_TODO = gql`
  mutation createTodo($description: String!) {
    createTodo(description: $description) {
      ...TodoFields
    }
  }
  ${TODO_FRAGMENT}
`;

const DELETE_TODO = gql`
  mutation deleteTodo($id: ID!) {
    deleteTodo(id: $id) {
      id
    }
  }
`;

const NEW_TODO_SUBSCRIPTION = gql`
  subscription {
    todoCreated {
      ...TodoFields
    }
  }
  ${TODO_FRAGMENT}
`;

const Todos = () => {
  const [inputValue, setInputValue] = useState('');
  const { data, error, loading } = useQuery(GET_TODOS);

  const saveTodo = useMutation(SAVE_TODO, {
    update: (proxy, mutationResult) => {
      proxy.writeQuery({
        query: GET_TODOS,
        data: { todos: data.todos.concat([mutationResult.data.createTodo]) },
      });
    },
  });

  const deleteTodo = useMutation(DELETE_TODO, {
    update: (proxy, mutationResult) => {
      const id = mutationResult.data.deleteTodo.id
      proxy.writeQuery({
        query: GET_TODOS,
        data: { todos: data.todos.filter(item => item.id !== id) },
      });
    },
  });

  const subData = useSubscription(NEW_TODO_SUBSCRIPTION);
  console.log(subData);

  if (loading) {
    return <div>Loading...</div>;
  };

  if (error) {
    return <div>Error! {error.message}</div>;
  };

  return (
    <>
      <h1>Todos</h1>
      {data.todos.map((item) => (
        <div key={item.id} className={styles.item}>
          <button onClick={() => {
            deleteTodo({
              variables: {
                id: item.id,
              },
            });
          }}>Delete</button>
          {' '}
          {item.description}
        </div>
      ))}
      <input
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        type="text"
      />
      <button onClick={() => {
        saveTodo({
          variables: {
            description: inputValue,
          },
        });
        setInputValue('');
      }}>Save</button>
    </>
  );
};

export default Todos;

这是根组件:

import React from 'react';
import { ApolloProvider } from 'react-apollo';
import { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks';

import Todos from 'components/Todos';
import apolloClient from 'config/apolloClient';

const App = () => (
  <ApolloHooksProvider client={apolloClient}>
    <Todos />
  </ApolloHooksProvider>
);

export default App;

有人知道我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

对不起,我知道了,这对我来说是一个愚蠢的错误。问题似乎出在我的apolloClient设置上:

import { split } from 'apollo-link';
import { getMainDefinition } from 'apollo-utilities';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { ApolloLink } from 'apollo-link';

import absintheSocketLink from 'config/absintheSocketLink';

const apolloClient = new ApolloClient({
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors)
        graphQLErrors.map(({ message, locations, path }) =>
          console.log(
            `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
          ),
        );
      if (networkError) console.log(`[Network error]: ${networkError}`);
    }),
    split(
      // split based on operation type
      ({ query }) => {
        const definition = getMainDefinition(query);
        return (
          definition.kind === 'OperationDefinition' &&
          definition.operation === 'subscription'
        );
      },
      new HttpLink({
        uri: 'http://localhost:4000/api/graphql',
        credentials: 'same-origin'
      }),
      absintheSocketLink,
    ),
  ]),
  cache: new InMemoryCache()
});

export default apolloClient;

上面代码中的错误是事实所在​​的行

      absintheSocketLink,

在错误的位置。应该在HttpLink之前。

愚蠢的我。