javascript - 使用带有异步获取变量的 react-apollo 调用 graphql 查询

标签 javascript reactjs asynchronous geolocation react-apollo

我有一个 react 组件,它会显示一张 map ,其中包含您附近的兴趣点。

我的 HOC 使用 react-apollo 查询这些兴趣点并将数据作为 props 提供给纯 UI 组件。

我正在尝试将用户的位置从 navigator.geolocation 获取到我的 graphql 查询的变量中。但由于导航器 API 是异步的,我似乎无法让它工作。

它看起来像这样:

const getCurrentPosition = async (settings = {}) =>
  new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject, settings);
  }
);

const query = gql`
  query($coordinates: [[Float]]){
    whatever(filter: {coordinates: $coordinates}) {
      _id
      coordinates
    }
  }
`;

const withData = graphql(query, {
  options: async (props) => {
    const position = await getCurrentPosition();

    return {
      variables: {
        coordinates: [position.coords.latitude, position.coords.longitude],
      },
    };
  },
  props: ({ data: { loading, whatever, refetch, variables: { coordinates } } }) => ({
    loading,
    whatever,
    coordinates,
    refetch,
  }),
});


const List = ({ loading, whatever, coordinates, refetch }) => {
  if (loading) {
    return null;
  }
  return (/* map display*/);
};

List.propTypes = {
  loading: React.PropTypes.bool.isRequired,
  whatever: React.PropTypes.array,
  coordinates: React.PropTypes.array,
  refetch: React.PropTypes.func,
};

export default withData(Map);

coordinates 在我的组件中始终为 null

当我记录事情时,似乎位置已经计算好了,但是 graphql 查询和组件渲染发生在它之前。

当我们获取用户位置时,不会调用查询并且不会重新呈现组件。

这可能吗?我做错了什么吗?

最佳答案

我会事先进行异步调用并通过 props 注入(inject)它然后使用 http://dev.apollodata.com/react/api.html#graphql-config.skip如果位置不在这里,则跳过查询。

也许使用 recompose/withProps 等?

关于javascript - 使用带有异步获取变量的 react-apollo 调用 graphql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42975208/

相关文章:

c# - 在 C# 中同步异步调用

apache - 使用 Apache 和 HAProxy 诊断 HTTP 500 错误

javascript - Swiper轮播IE11 bug : images are overstretched

reactjs - 使用 Apollo 查询闪烁

reactjs - 如何使用react-testing-library为react ui Menu触发onClose?

javascript - 当元素仅添加到末尾时,可以使用索引作为键吗?

c# - 在 C# 中的自定义验证属性中使用异步方法

javascript - 无法从 Hacker News API 调用 JSON 数据

javascript - 无符号右移函数不适用于负输入

javascript - 将变量传递到近球体(Error Obj Obj)#appcelerator