Thiago Nascimento
Thiago Nascimento

Reputation: 1155

GraphQL query using React Native AsyncStorage

I'm trying to build an component, using React Native and Apollo Client that execute the following Query:

query getTable($tableId:String!){
   getTable(id:$tableId){
      users{
      name
      imageURL
   }
}

So, as you the query above have a variable called tableId and that value is stored using the AsyncStoragemethod. Is there a way that I can get the value from the AsyncStorage and use it as query variable.

I tried to do the following but it didn't work:

graphql(Query, {
  options: {
    tableId: await AsyncStorage.getItem('table'),
  },
})(MyComponent);

Upvotes: 1

Views: 1531

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84877

In my opinion, the preferred way of doing this would look like this:

Call AsyncStorage.getItem() in a parent component and then pass the result down as a prop to MyComponent. As illustrated in the docs, options can be a function instead of an object, in which case it gets the component's props passed to it as its first argument. So, assuming the prop is called tableId, your HOC would look like this:

graphql(Query, { options: ({ tableId }) => ({ variables: { tableId } }) })

Alternatively, you could set up the query with some default value:

graphql(Query, { options: { variables: { tableId : 'foo' } } })

You would call AsyncStorage.getItem() in your component's componentDidMount() method and assign the result to your component's state. Your component will have a data prop available to it when it renders. You can call this.props.data.refetch({ tableId: this.state.tableId }) from your render function to force the query to update with the newly available id.

I think that's a lot less clean than the first option, and will require additional logic to keep your component from calling refetch or rerendering unnecessarily... but it should still work if for some reason you don't want to change the parent component.

Upvotes: 2

Related Questions