如何使用 React-query 通过按钮触发请求?

How to trigger requests with a button using React-query?

我一直在尝试学习 React-query,但似乎无法通过我的 onSubmit 事件触发请求。现在,代码正在发送带有“washington”作为默认参数的请求并将其打印到屏幕上,新请求也会触发 onBlur 事件,并在输入的城市有效时获取数据。

我希望我可以将此逻辑移至 submit() 函数,处理输入数据,并且仅当数据有效时才继续发出请求。这是我使用免费 apiKey 重现问题的 stackblitz:StackBlitz

这是代码:

import React, { useState } from 'react';
import { useQuery } from 'react-query';
import axios from 'axios';

const Fetch = async city => {
  let apiKey = '91b5ff77e9e7d1985a6c80bbbb3b2034';
  const { data } = await axios.get(
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`
  );
  return data;
};

const Weather = () => {
  const [city, setCity] = useState('washington');
  const { data, error } = useQuery(['temperature', city], () => Fetch(city));

  const submit = () => {};

  return (
    <div>
      <form onSubmit={submit}>
        <input onBlur={e => setCity(e.target.value)} type="text" />
        <button type="submit">send</button>
      </form>
      {!data ? null : <div>{data.main.temp}</div>}
    </div>
  );
};

export default Weather;

您可以使用 useMutation hooks。正如文档所说 mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, React Query exports a useMutation hook.。此挂钩将 return 一个对象,为您提供突变函数,您可以使用该函数根据用户交互触发请求。

const { mutate: renamedMutationFunction } = useMutation(newTodo => axios.post('/todos', newTodo)).

然后在您的代码中的某处,您可以执行以下操作:

const handleClick = () => { renamedMutationFunction(); //invoking the mutation }

编辑

请参阅@TkDodo 的回答以获得更好的解决方案。你基本上可以重新设置城市,react-query 会自动重新获取数据。

你也可以在表单的onSubmit事件中调用setCity,因为onSubmit事件在提交事件中获取完整提交的表单:

<form
  onSubmit={(event) => {
    event.preventDefault();
    const city = new FormData(event.currentTarget).get("city");
    // do validation here
    if (isValid(city)) {
      setCity(city)
    }
>
  <input name="city" type="text" />
  <button type="submit">send</button>
</form>

确保为您的输入提供 name 以便您可以从表单提交事件中获取它。