【问题标题】:React Apollo fetch onceReact Apollo fetch 一次
【发布时间】:2021-02-08 13:39:16
【问题描述】:

我正在研究简单的 COVID-19 追踪器,但我遇到了问题。 Apollo 中是否有任何选项可以让 React 每次按下按钮时获取一次 graphql 数据?

现在我有 TextInput 和 Button,但是当我获取数据时,我无法在输入中输入另一个国家/地区,因为我立即出现错误。

const Tile = () => {
  const [country, setCountry] = useState('Poland');
  const [cases, setCases] = useState(0);

  const MY_QUERY = gql`
    query getCountryStats($country: String!) {
      country(name: $country) {
        todayCases
      }
    }
  `;

  const [getCountryStats, {data, loading, error}] = useLazyQuery(MY_QUERY, {
    variables: {
      country: country,
    },
    onCompleted: (data) => {
      setCases(data.country.todayCases);
    },
  });

  if (loading) return <Text>LOADING...</Text>;
  if (error) return <Text>Error!</Text>;

  return (
    <View>
      <CasesNumber>{cases}</CasesNumber>
      <FinderWrapper>
        <FinderInput
          onChangeText={(text) => {
            setCountry(text);
          }}
        />
        <FinderButton
          onPress={() => {
            getCountryStats();
          }}>
          <Text>FIND</Text>
        </FinderButton>
      </FinderWrapper>
    </View>
  );
};

export default Tile;

【问题讨论】:

    标签: react-native react-apollo apollo-client


    【解决方案1】:

    试试这个

    const Tile = () => {
      const [country, setCountry] = useState('Poland');
      const [cases, setCases] = useState(0);
    
      let inputValue = ‘’;
    
    
      const MY_QUERY = gql`
        query getCountryStats($country: String!) {
          country(name: $country) {
            todayCases
          }
        }
      `;
    
      const [getCountryStats, {data, loading, error}] = useLazyQuery(MY_QUERY, {
        variables: {
          country: country,
        },
        onCompleted: (data) => {
          setCases(data.country.todayCases);
        },
      });
    
      const onGetCountryStats = () => {
        
        setCountry(inputValue);
        getCountryStats();
      }
    
      if (loading) return <Text>LOADING...</Text>;
      if (error) return <Text>Error!</Text>;
    
      return (
        <View>
          <CasesNumber>{cases}</CasesNumber>
          <FinderWrapper>
            <FinderInput
              onChangeText={(text) => {
               inputValue = text;
              }}
            />
            <FinderButton
              onPress={() => {
               onGetCountryStats();
              }}>
              <Text>FIND</Text>
            </FinderButton>
          </FinderWrapper>
        </View>
      );
    };
    
    export default Tile;
    

    【讨论】:

      猜你喜欢
      • 2017-10-05
      • 2020-02-27
      • 2019-07-26
      • 2020-10-13
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 2022-12-13
      • 2020-02-04
      相关资源
      最近更新 更多