尝试使用React和Apollo中的单个输入来管理两个搜索查询

时间:2019-03-09 18:26:40

标签: reactjs graphql apollo react-apollo

节点:v10.15.2 反应:“ ^ 16.8.3”, react-apollo:“ ^ 2.5.2”, react-dom:“ ^ 16.8.3”,

我可以使用一个过滤器,但是无法找出分离值的最佳方法,因此两个过滤器都不相同。

我尝试使用嵌套查询无济于事。

import React, { Component } from "react";
import { Query } from "react-apollo";
import gql from "graphql-tag";
import Cocktail from "../Cocktail";
import styles from "./styles.module.css";

const GET_COCKTAIL_NAMES = gql`
  query DrinksQuery($sort: String, $where: JSON) {
    cocktails(sort: $sort, where: $where) {
      _id
     name
     ingredients
    }
  }
`;

class CocktailList extends Component {
  state = {
    data: {
      cocktails: []
    }
  };

  filterList = event => {
    const typedWord = event.target.value
    this.setState({
      data: {
        // ingredients_contains: typedWord,
        name_contains: typedWord
      }
    });
  };

  render() {
    return (
      <section className={styles.list}>
        <form>
          <fieldset>
            <label>
              <span className="visually-hidden">
                Filter by name or search by ingredient
              </span>
              <input
                type="text"
                className="Search"
                placeholder="Filter by name or search by ingredient"
                onChange={this.filterList}
              />
            </label>
          </fieldset>
        </form>
        <Query
            query={GET_COCKTAIL_NAMES}
            variables={{
              sort: "name: ASC",
              where: {
                // name_contains: this.state.data.name_contains,
                ingredients_contains: 
this.state.data.ingredients_contains
              }
            }}
          >

          {({ loading, error, data }) => {
            if (loading) return null;
            if (error) return `Error: ${error}`;
            return (
              <div>
                {data.cocktails.map(({ name, _id, ingredients }) => {
                  return (
                    <Cocktail
                      key={_id}
                      id={_id}
                      name={name}
                      ingredients={ingredients}
                    />
                  );
                })}
              </div>
            );
          }}
        </Query>
      </section>
    );
  }
}

export default CocktailList;

我在https://cocktail-list-client.herokuapp.com/有一个使用REST和axios的工作分支,但想转换为Apollo和graphql作为学习练习。任何帮助是极大的赞赏。谢谢!

0 个答案:

没有答案