React-apollo: how to pass query variables to query

Created on 18 Dec 2017  路  16Comments  路  Source: apollographql/react-apollo

/* eslint-disable*/

import React, { Component } from 'react'
import ItemsList from './ItemsList'
import { Stats, BigBreadcrumbs, WidgetGrid, JarvisWidget } from '../components'
import Datatable from './tables/Datatable'
import SparklineContainer from './graphs/inline/SparklineContainer'
import CreateItem from './createItem.js'
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { log } from 'core-js/library/web/timers';
import Itemtable from './itemTable.js';

class Items extends Component {
constructor(props) {
super(props);
this.handleSearch = this.handleSearch.bind(this);
this.state = {
searchText: '',
searchResult: []
}
render(){
return(



{ /* code to display data from getItemInfo */ }

)
}

}

const query = gql query getItemInfo($name:String){ getItemInfo(name:$name){ id, name }, items{ id, name } }
export default graphql(query, {
options: {
variables: {
name: "%Agent%"
}
}
}
)(Items);

expected - set state then pass state value to query

Most helpful comment

@julianmnst

Try using option

export default graphql(QueryTodos, {
  options: (props) => ({ variables: { userId: props.userId } })
})( Home );

All 16 comments

@ketankulkarni have you found a solution for your issue ? if so ! can you help me please? I have the same issue. Thank you

@mauscoelho what about with the graphql() function? There are no examples for that.

@julianmnst I didn't understand your question, but if you are trying to do a request without a component you can see the query interface here

it's something like that

import client from '...';

await result = client.query({ query: YOUR_QUERY, variables: { });

@julianmnst

Try using option

export default graphql(QueryTodos, {
  options: (props) => ({ variables: { userId: props.userId } })
})( Home );

I also believe that by default the HOC created by graphql will look for needed variable names on incoming props. So if props.userId passed in (as in the example above) to the HOC, I think this would work also

// pulls `userId` from incoming props
export default graphql(QueryTodos)( Home );

@jiradeto
Your solution worked for me. Thanks.

@julianmnst

using option

export default graphql(QueryTodos, {
  options: (props) => ({ variables: { userId: props.userId } })
})( Home );

Now how do you call that QueryTodos Query?? Is it something like this.props.sth?

How can I use a result from the last graphql as a variable in second request? This is not working...

compose(
  graphql(readOfferQuery, {
    name: 'readOfferQuery',
    options: ({ id, slug }) => ({
      variables: {
        [id ? 'id' : 'slug']: id ? id : slug
      }
    })
  }),
  graphql(featuredOffersQuery, {
    name: 'featuredOffersQuery',
    options: ({ readOfferQuery }) => {
      return {
        variables: {
          limit: 20,
          prizes: readOfferQuery.readOffer.prizes,
          type: readOfferQuery.readOffer.type
        }
      };
    }
  })
)

@gcfabri this would be easier without the HOC - use the <Query /> component and nest another that uses the result.

@gcfabri Not sure if this is still relevant for you, but I did exactly what is described here https://stackoverflow.com/a/49320606/1238150 and it worked for me. Maybe this helps you too.

@natterstefan thanks, but I used the <Query /> component. I was having problems with skip andgraphql HOC as in this StackOverflow example.

import { withFormik } from "formik";
import React from "react";
import { compose, graphql } from "react-apollo";
import * as Yup from "yup";
import { createUser } from "../queries/user";

export const createUser = gql`
  mutation($email: String!, $password: String!) {
    createUser(userInput: { email: $email, password: $password }) {
      _id
      email
    }
  }
`;



md5-5b9c111c9d393c65a8ce7435ecaa4eb8



const LoginForm = props => {
  const {
    values,
    touched,
    errors,
    isSubmitting,
    handleChange,
    handleBlur,
    handleSubmit
  } = props;

  return (
    <form onSubmit={handleSubmit}>
      <h4 className="card-title">Login</h4>
      <div className="form-group">
        <label>Email</label>
        <input
          name="email"
          type="text"
          className={`form-control ${errors.email &&
            touched.email &&
            "is-invalid"}`}
          value={values.email}
          onChange={handleChange}
          onBlur={handleBlur}
        />
        {errors.email && touched.email && (
          <div className="invalid-feedback">{errors.email}</div>
        )}
      </div>
      <div className="form-group">
        <label>Password</label>
        <input
          name="password"
          type="password"
          className={`form-control ${errors.password &&
            touched.password &&
            "is-invalid"}`}
          value={values.password}
          onChange={handleChange}
          onBlur={handleBlur}
        />
        {errors.password && touched.password && (
          <div className="invalid-feedback">{errors.password}</div>
        )}
      </div>

      <div className="form-group m-0">
        <button
          type="submit"
          className="btn btn-primary btn-block"
          disabled={isSubmitting}
        >
          {isSubmitting ? "Wait Please" : "Login"}
        </button>
      </div>
      <div className="mt-4 text-center">
        Don't have an account? <a href="register.html">Create One</a>
      </div>
    </form>
  );
};



md5-5b9c111c9d393c65a8ce7435ecaa4eb8



export default compose(
  graphql(createUser),
  withFormik({
    mapPropsToValues: () => ({ email: "", password: "" }),

    validationSchema: Yup.object().shape({
      email: Yup.string()
        .email("E-mail is not valid!")
        .required("This field is requuired !"),
      password: Yup.string().required("This field is requuired !")
    }),

    handleSubmit: async (
      values,
      { props: { mutate }, setSubmitting, resetForm }
    ) => {
      try {
        const { data } = await mutate({
          variables: values
        });
        setSubmitting(false);
        console.log(data);
      } catch (error) {
        setSubmitting(false);
        console.log(error);
      }
    }
  })
)(LoginForm);

@SteveAtSentosa i was wondering why the hellll was this working

export default compose(graphql(TRIBE_ALL_MEMBERS_QUERY, {
  props: ({ data: { memberStatus } }) => ({ memberStatus }),
}))(({ memberStatus, isTribeOwner }) => (

if i never pass any variables: {...} the component was called like

<TribeMemberButton isTribeOwner={tribeOwner === _id} tribeId={tribeId} profileId={_id} />

jajaj, your comment just help me think i'm not stupid/crazy

Going through the documentation from a frontend point of view makes sense, but having to build the API and the Frontend myself Its a bit confusing. on the example on the documentation there is

query Dog($breed: String!) {
    dog(breed: $breed) {
        // some code
    }
}

But where is that uppercase Dog defined? and the lowercase dog ? Would be useful to see the client part of the examples.

@andrevenancio the Dod is just an alias for your query. The dog is defined in the schema in your API. You can take a look in this site for more explanation.

Was this page helpful?
0 / 5 - 0 ratings