简体   繁体   English

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

[英]Call graphql query with react-apollo with asynchronously fetched variables

I've got a react component which displays a map with points of interest near you. 我有一个react组件,它显示一个地图,其中包含您附近的景点。

My HOC uses react-apollo to query for those points of interests and give the data as props to the pure UI component. 我的HOC使用react-apollo来查询那些兴趣点,并将数据作为道具提供给纯UI组件。

I'm trying to get the position of the user from navigator.geolocation into the variables of my graphql query. 我正在尝试将用户的位置从navigator.geolocation放入我的graphql查询的变量中。 But since the navigator API is asynchronous, I can't seem to make it work. 但是由于导航器API是异步的,所以我似乎无法使其正常工作。

It looks about like this : 它看起来像这样:

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 is always null inside my component. 在我的组件中, coordinates始终为null

When I log things, it seems that the position is computed but the graphql query and the component rendering happen before it. 当我记录日志时,似乎已经计算了位置,但是graphql查询和组件渲染在此之前发生。

The query is not recalled and the component not re-rendered when we get the user location. 获取用户位置后,将不会重新调用查询,也不会重新呈现组件。

Is it possible ? 可能吗 ? Am I doing something wrong? 难道我做错了什么?

I would make the asynchronous call beforehand and inject it through props then use http://dev.apollodata.com/react/api.html#graphql-config.skip to skip the query if the position is not here yet. 我会事先进行异步调用,并通过道具将其注入,然后使用http://dev.apollodata.com/react/api.html#graphql-config.skip跳过该查询(如果位置不在此处)。

Maybe using recompose/withProps, etc. ? 也许使用recompose / withProps等?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM