标签: react-apollo

react-apollo 网络错误:查询“Hello”缺少服务器响应

我正在尝试使用以下代码设置 react-apollo:

import React from 'react';
import {render} from 'react-dom';

import gql from 'graphql-tag';
import { ApolloProvider, graphql } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';


const client = new ApolloClient({
  link: new HttpLink({ uri: 'http://localhost:5000/graphql' }),
  cache: new InMemoryCache()
});



class App extends React.Component {
  render () {
    return <p> Hello React project</p>;  }
}
const MY_QUERY = gql`query Hello { hello }`;

const AppWithData = …
Run Code Online (Sandbox Code Playgroud)

javascript apollo reactjs graphql react-apollo

5
推荐指数
1
解决办法
3649
查看次数

Apollo GraphQL (React) 跨组件数据共享

我刚开始使用 react-apollo,想知道跨组件共享数据的最佳方式是什么。

例如,我componentA使用grapqlfromreact-apollo来获取一些数据 ( WrappedA)。我还有一些其他组件,componentB在我的 UI 中的其他地方,并且想要使用已经由componentA. 下面附上一个非常简单的例子。

const ComponentA = ({ ...props }) => (
    <div>
        ComponentA...
        id: {props.organisationsData.organisations.id}
    </div>
)

const ComponentB = ({ ...props }) => (
    <div>
    ****** Want to access props.organisationsData *****
    ComponentB...
    </div>
)

const organisationsQuery = gql`
    query organisations {
        organisations {
            id
            name
        }
    }
`

const WrappedA = graphql(organisationsQuery, { name: 'organisationsData' })(WrappedA)

const Container = ({ ...props }) => …
Run Code Online (Sandbox Code Playgroud)

apollo graphql react-apollo apollo-client

5
推荐指数
1
解决办法
1410
查看次数

使用 writeFragment 更新属于对象的字段?

我正在努力让我的第一个writeFragment工作。

这是对象形状:

resolutions {
  _id
  name
  completed
  goals {
    _id
    name
    completed
  }
}
Run Code Online (Sandbox Code Playgroud)

我刚刚在客户端上运行了一个成功添加 new 的突变goal,现在我试图让客户端页面自动更新并显示刚刚添加的新目标。

我有readFragment工作。它成功读入决议。我正在阅读决议,而不是目标,因为作为属于决议的领域,目标没有自己的 id。

这是我的update函数,显示readFragmentwriteFragment

resolutions {
  _id
  name
  completed
  goals {
    _id
    name
    completed
  }
}
Run Code Online (Sandbox Code Playgroud)

...这是片段的gql:

   const GET_FRAGMENT_GOAL = gql`
    fragment targetRes on resolutions {
      name
      completed
      goals {
        _id
        name
        completed
      }
    }
  `;


  const SET_FRAGMENT_GOAL = gql`
    fragment targetGoal on resolutions {
      __typename
      goals
    }
  `;
Run Code Online (Sandbox Code Playgroud)

这是我收到的控制台错误:

您正在使用简单(启发式)片段匹配器,但您的查询包含联合或接口类型。

Apollo …

apollo graphql react-apollo apollo-client

5
推荐指数
1
解决办法
4036
查看次数

refetchQueries onComplete 回调

是否可以添加在 refetchQueries 完成时调用的回调函数?问题是我不希望在后台发生突变后重新获取,因为如果数据没有立即更新然后突然更新,这可能会使用户感到困惑。提交函数可能如下所示:

async submit(values) {
  this.setState({ submitting: true })
  validateUrl(values.url).then((response:Response) => {
    response.json().then((data) => {
      if (data.length > 0) {
        this.onError("Invalid url")
        this.setState({ submitting: false })
      } else {
        this.props.mutate({
          variables: values,
          refetchQueries: [{ query: LinksQuery}]
        }).then(() => {
          this.props.navigation.pop(2)
          this.props.navigation.state.params.showSuccessFeedback()
          this.setState({ submitting: false })
        });
      }
    });
  })
}
Run Code Online (Sandbox Code Playgroud)

但是我不想在 LinksQuery 的重新获取完成之前返回。

一种解决方案是使用 graphql() 装饰器将 Query 添加到组件,然后使用 refetch() 返回一个承诺。但是在 refetchQueries 选项中使用它会更干净。特别是如果应该重新获取多个查询。

react-apollo的版本是1.4.15,不过如果能解决问题我可能愿意升级到react-apollo 2.*

react-native react-apollo

5
推荐指数
1
解决办法
3569
查看次数

React Apollo 从状态动态创建查询

这是一个模型情况我的数据库中有一些字段可以说颜色,大小,高度......

我可以获取这些字段并将其显示给可以选择这些字段的用户,然后将它们设置为组件状态

我想要实现的是从存储在状态中的这些字段动态创建 GQL 查询(而不是查询变量)

例子

//import react gql ....
class MyComponent extends Component {

constructor(props){
   super(props)
   this.state = {
     fields : []
   }
}

render(){
...
}

componentWillMount(){
    fetch(...)
      .then(fields => this.setState({fields}))
   }

}

export default graphql( --->state => CREATE_QUERY_DYNAMICALLY_FROM_FIELDS(state.fields)<----,{..some options})
Run Code Online (Sandbox Code Playgroud)

有没有办法在查询创建期间访问组件状态?

或者其他一些方法?

任何想法表示赞赏

apollo reactjs graphql react-apollo

5
推荐指数
2
解决办法
3660
查看次数

使用 Apollo 缓存具有多个 id 的 GraphQL 查询

我们正在 Web 应用程序中使用 apollo 客户端,并且正在寻找提高缓存使用率的方法。

我们有一个查询,需要一个ID数组作为参数与IDS的一个例子查询foobar看起来像这样:

query routes {
  routes(routeNames: ["foo", "bar"]) {
    items {
      name
      route
      defaults
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

缓存设置如下所示:

export const cacheRedirects = {
  Query: {
    routes: (_: any, args: RoutesArgs, { getCacheKey }: Resolver<'name'>): Array<CacheKey> =>
      args.routeNames.map(name => getCacheKey({ __typename: 'Route', name })),
  },
};

export const dataIdFromObject = (object: QueryResult): ?string => {
  switch (object.__typename) {
    case 'Route':
      return `${object.__typename}:${object.name}`;
    default: return defaultDataIdFromObject(object);
  }
};

export function newCache(): InMemoryCache {
  return …
Run Code Online (Sandbox Code Playgroud)

caching apollo graphql react-apollo apollo-client

5
推荐指数
1
解决办法
1569
查看次数

如何在 apollo-link-error 中访问 apollo 客户端到 resetStore?

我正在构建一个基于JWT.

JWT已过期。当JWT到期时,我抓住JWT使用过期的错误apollo-link-error。我想调用apolloClient.resetStore()方法来重置缓存。

这是我的代码:

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(error => {
      // console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
      if (error.code === 1001) {
        auth.signout();

        // how can I get apollo client here?
        //client.resetStore();
      }
    });
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const client = new ApolloClient({
  cache,
  link: from([authMiddleware, errorLink, terminalLink])
});
Run Code Online (Sandbox Code Playgroud)

我不确定apollo-link-error是处理 expired 错误的正确位置JWT

apollo react-apollo apollo-client

5
推荐指数
1
解决办法
2521
查看次数

带有 React-Apollo 的 React-Select 不起作用

我们正在使用 react-select 并根据用户类型获取项目。我无法使其与 react-apollo 一起使用。

有人可以帮我提供指导吗?

这是我失败的尝试:

class PatientSearchByPhone extends Component {
  updateProp = mobile => {
    if (mobile.length < 10) return;
    this.props.data.refetch({ input: { mobile } });
  };

  render() {
    console.log(this.props.data);
    return <AsyncSelect cacheOptions loadOptions={this.updateProp} />;
  }
}

const FETCH_PATIENT = gql`
  query Patient($input: PatientSearchInput) {
    getPatients(input: $input) {
      id
      first_name
    }
  }
`;
export default graphql(FETCH_PATIENT, {
  options: ({ mobile }) => ({ variables: { input: { mobile } } })
})(PatientSearchByPhone);
Run Code Online (Sandbox Code Playgroud)

版本:
“反应阿波罗”:“^2.1.11”,
“反应选择”:“^2.1.0”

谢谢你的时间。

apollo reactjs react-select graphql react-apollo

5
推荐指数
1
解决办法
1953
查看次数

Apollo 查询从缓存中获取了错误的数据

Apollo 查询在我的 React 应用程序中缓存了错误的数据。

如果我将查询的 fetchPolicy 设置为“仅网络”,则一切正常。

所以我认为这是一个缓存问题。

一直在努力解决问题,看到了关于apollo cache的文章,还是解决不了问题。

以下是我查询后的结果:

参数 memberId 为空(结果正确)

[
  {
    "id": 87,
    "totalQuantity": 12,
    "Orders": [
      {
        "id": 1,
        "quantity": 11,
        "Member": {
          "id": 1,
          "name": "A"
        }
      },
      {
        "id": 28,
        "quantity": 1,
        "Member": {
          "id": 9,
          "name": "B"
        }
      }
    ]
  },
  {
    "id": 88,
    "totalQuantity": 1,
    "Orders": [
      {
        "id": 2,
        "quantity": 1,
        "Member": {
          "id": 1,
          "name": "A"
        }
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

参数 memberId 为 9(结果正确)

[
  {
    "id": …
Run Code Online (Sandbox Code Playgroud)

node.js apollo reactjs react-apollo apollo-client

5
推荐指数
1
解决办法
1443
查看次数

如何在 Apollo Client 中使用没有 JSX 组件的 client.query?

我正在尝试使用 React 在 Apollo Client 中进行查询而不返回 JSX 组件,只是一个对象(data向 Apollo Server 进行常见查询时收到的对象)。

我尝试使用<Query />组件,但它返回一个 React 节点,我只需要一个对象。该文档仅解释了在某些时候返回 JSX 组件的方法,当我要做的只是发送请求并在回调中处理响应时。

实际上我正在尝试这种方式(我在 React 中使用 TypeScript):

import React from 'react';
import { withApollo } from 'react-apollo';
import gql from 'graphql-tag';

const MY_QUERY = gql`
  query MY_QUERY {
    myQuery {
      attr1
      attr2
    }
  }
`;

const res = ({ client }: { client: any }) =>
  client
    .query(MY_QUERY)
    .then((data: { data: any }) => data);

withApollo(res);

console.log(res);
Run Code Online (Sandbox Code Playgroud)

有了这个,我正在寻找一个像

{
  "data": {
    "myQuery": …
Run Code Online (Sandbox Code Playgroud)

apollo reactjs graphql react-apollo apollo-client

5
推荐指数
1
解决办法
3552
查看次数