很棒的防弹承诺。获取对“查询”的引用

时间:2019-09-14 16:09:53

标签: reactjs graphql-js debounce

在下面的代码中,我使用awesome-debounce-promise中的AwesomeDebouncePromise来“去抖动”对外部graphQL API的调用。根据{{​​3}},在“ searchAPI”函数之内,“获取”数据的正确位置。

在我的代码中,在调用handleTextChange之后,我将实际的“ API调用”放在了await this.props.client.query(...)await searchAPIDebounced())中。这使得代码的行为几乎与我期望的一样。我的API调用仅每500毫秒触发一次。

但是,最好将API调用(this.props.client.query(...))放在searchAPI函数中(应该在该位置)。我面临的问题是我不知道如何在searchAPI函数中获取对this.props.client.query的引用。

有什么主意吗?

import React from 'react';
import AwesomeDebouncePromise from 'awesome-debounce-promise';
import gql from 'graphql-tag'
import { withApollo } from 'react-apollo'
import { Link } from 'react-router-dom'

const USER_SEARCH_QUERY = gql`
  query ($filter: String!) {
    user(login: $filter) {
      login
      name
    }
  }
`;

const searchAPI = filter => filter;

const searchAPIDebounced = AwesomeDebouncePromise(searchAPI, 500);

class SearchInputAndResults extends React.Component {
  state = {
    filter: '',
    results: null,
    user:null,
    notFound: false
  };

  handleTextChange = async filter => {
    this.setState({ filter, results: null }); 
    await searchAPIDebounced(filter);

    try {
      if(filter === '') {
        this.setState({notFound:false, user:null })
      } else {
        const result = await this.props.client.query({
          query: USER_SEARCH_QUERY,
          variables: { filter },
        })
        console.log(result);
        this.setState({ notFound: false, user: result.data.user });
      }

    } catch(err) {
      this.setState({notFound: true, user:null});
    }
  };

  componentWillUnmount() {
    this.setState = () => {};
  }

  render() {
    return (
      <div>
        <div>
          Search for any Github user:
          <input
            className="form-control input-lg"
            type='text'
            onChange={e => this.handleTextChange(e.target.value)}
          />
        </div>
        {this.state.notFound &&
        <div className="card">
          <div className="card-body">
            No Github profile found with this username.
          </div>
        </div>
        }

        {this.state.user &&
        <div className="card">
          <div className="card-body">
          {console.log(this.state.user)}
            User: { this.state.user.login }<br />
            Name: { this.state.user.name}
            <Link to={`/user/${this.state.user.login}`}>Show full info</Link>
          </div>
        </div>
        }

      </div>
    )
  }

}

export default withApollo(SearchInputAndResults);

0 个答案:

没有答案