【问题标题】:Call graphql query with react-apollo with asynchronously fetched variables使用带有异步获取变量的 react-apollo 调用 graphql 查询
【发布时间】:2017-08-15 22:59:29
【问题描述】:

我有一个react 组件,它显示了一张地图,上面有你附近的景点。

我的 HOC 使用 react-apollo 来查询这些兴趣点,并将数据作为道具提供给纯 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 查询和组件渲染发生在它之前。

当我们获取用户位置时,查询不会被召回并且组件不会重新渲染。

有可能吗?我做错了吗?

【问题讨论】:

    标签: javascript reactjs asynchronous geolocation react-apollo


    【解决方案1】:

    我会事先进行异步调用并通过 props 将其注入,然后如果该位置尚未出现,则使用 http://dev.apollodata.com/react/api.html#graphql-config.skip 跳过查询。

    也许使用 recompose/withProps 等?

    【讨论】:

    • 最终做了一个 HOC,它异步检索当前位置并在之后更新其状态。我将只显示一个加载器,直到我们获得当前位置,然后显示初始化到正确中心的地图。
    • 能否展示一下代码,让我看看它是如何工作的?
    猜你喜欢
    • 2018-09-25
    • 2017-02-21
    • 2018-01-27
    • 2019-01-28
    • 2018-03-02
    • 1970-01-01
    • 2020-11-04
    • 2019-01-26
    • 2018-02-10
    相关资源
    最近更新 更多