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

时间:2021-07-05 19:37:36

标签: javascript reactjs react-hooks react-query

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

问题是希望我可以将此逻辑移至 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;

2 个答案:

答案 0 :(得分:2)

您也可以在表单的 setCity 事件中调用 onSubmit,因为 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,以便您可以从表单提交事件中获取它。

答案 1 :(得分:0)

您可以使用 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.。此钩子将返回一个对象,该对象为您提供一个突变函数,您可以使用该函数根据用户交互触发请求。

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

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

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

编辑

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