apollographql / apollo-link-state

✨ Manage your application's state with Apollo!
MIT License
1.4k stars 101 forks source link

How to pass variable from local state #328

Open pippo111 opened 5 years ago

pippo111 commented 5 years ago

I have simple Query with variable:

<Query
  pollInterval={2000}
  variables={{ programId: activeProgram }}
  query={FETCH_PROGRAM_EDITOR}
>...

with query:

const FETCH_PROGRAM_EDITOR = gql`
  query ProgramEditor($programId: String!) {
    program(_id: $programId) {
      _id
      name
      desc
    }
  }`

activeProgram is coming from local state (cache). Is there a way to use local state variables directly in query ? How to pass local state to query variable ?

jangerhofer commented 5 years ago

For better or worse, at present, I believe that the simplest way to pass a local variable is simply to compose two Query components -- the remote component inside of the local component.

Something like this, where the first query matches the structure of your local cache:

<Query
    query={gql`
      query getActiveProgram {
        activeProgram @client {
          id
        }
      }
    `}
  >
    {({
      data: {
        activeProgram: { id }
      }
    }) => <Query query={FETCH_PROGRAM_EDITOR} variables={{programId: id}}>
        {() => ...}
    </Query>}
</Query>

The good news is that, according to this slide from a presentation given at the beginning of the month, an @export directive will soon be available to solve the same problem!

EDIT: See this PR in the Apollo Client repo for the release of the features from the aforementioned slide.

tanaypratap commented 5 years ago

Wouldn't this solve your problem? https://www.apollographql.com/docs/react/essentials/local-state.html#combine-data

I'm new to Apollo and exploring a lot of use cases for a new app.