javascript 将useQuery挂接结果集设置为加载而不调用

to94eoyn  于 2023-01-08  发布在  Java
关注(0)|答案(2)|浏览(132)

我试图在我的新项目中建立一个搜索栏,我似乎做错了一些事情(也许很多)。
我将book state设置为null,useQuery钩子似乎正在使用它来搜索书籍。
我不想让它搜索任何东西,除非我单击按钮。
这是我的密码
fetchBooks.jsx

async function fetchBooks({ queryKey }) {
  const book = queryKey[1];

  const response = await fetch(
    `https://www.googleapis.com/books/v1/volumes?q=${book}`
  );
  if (!response.ok) {
    throw new Error(`Search not found for ${book}`);
  }
  return response.json();
}

export default fetchBooks;

这是主要的组成部分。

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import fetchBooks from "../helper/fetchBooks";

const Home = () => {

    const [book, setBook] = useState(null);

    const results = useQuery(["search", book], fetchBooks);

    const handleSubmit = (e) => {
        e.preventDefault();
        setBook(e.target.elements.book.value);
    };

    return (
        <>
            <form onSubmit={handleSubmit}>
                <label htmlFor="book">
                    Book Name:
                    <input type="text" name="book" />
                </label>
                <button type="submit">Submit</button>
            </form>

            {results.isLoading ? (
                <div>Loading...</div>
            ) : results.isError ? (
                <div>{results.error.message}</div>
            ) : (
                <div>
                    <h2>Results</h2>
                    <ul>
                        {results.data.items.map((item) => {
                            return (
                                <div key={item.id}>
                                    <h3>{item.volumeInfo.title}</h3>
                                    <p>{item.volumeInfo.authors}</p>
                                </div>
                            );
                        })}
                    </ul>
                </div>
            )}
        </>
    );
};

export default Home;
c8ib6hqw

c8ib6hqw1#

如果book为null,可以在fetch函数中返回一个默认值,这样,查询就不会实际请求API。

async function fetchBooks({ queryKey }) {
  const book = queryKey[1];

  if(!book) return { items: [] }

  const response = await fetch(
    `https://www.googleapis.com/books/v1/volumes?q=${book}`
  );
  if (!response.ok) {
    throw new Error(`Search not found for ${book}`);
  }
  return response.json();
}

export default fetchBooks;
vc9ivgsu

vc9ivgsu2#

如果book设置为null,您可以修改fetchBooks函数以返回空数组,而不是限制useQuery调用fecthBooks函数。fetchBooks可以修改如下:-

async function fetchBooks({ queryKey }) {
  const book = queryKey[1];
  if(!book){
    return { 
              isLoading : false,
              error : null,
              data : null
           }
  }
  const response = await fetch(
    `https://www.googleapis.com/books/v1/volumes?q=${book}`
  );
  if (!response.ok) {
    throw new Error(`Search not found for ${book}`);
  }
  return response.json();
}

export default fetchBooks;

相关问题