简体   繁体   English

单击按钮时创建新的获取请求 - SWR / React

[英]Create a new fetch request on button click - SWR / React

I am building a trivia app using the OpenTBD API.我正在使用OpenTBD API 构建一个琐事应用程序。

I use SWR to make my API requests and get the questions and answers I want to display when my component renders我使用 SWR 发出我的 API 请求并获得我想要在我的组件呈现时显示的问题和答案

API call: API 拨打:

import useSWR from "swr";

export function useFetch(category, amount, difficulty) {
  const url = `https://opentdb.com/api.php?amount=${amount}&category=${category}&difficulty=${difficulty}&type=multiple`;
  const fetcher = (...args) => fetch(...args).then((res) => res.json());

  const { data, error } = useSWR(url, fetcher, {
    revalidateOnFocus: false,
  });

  return {
    data: data,
    isLoading: !error && !data,
    isError: error,
  };
}

Component:成分:

function Quiz() {
  const { category, color } = useSelector((state) => state.start);
  const { amount, difficulty } = useSelector((state) => state.settings);
  const gameEnded = useSelector((state) => state.end.isEnded);
  const dispatch = useDispatch();

  const { data, isLoading, isError } = useFetch(category, amount, difficulty);

  if (isLoading) {
    return <FlowerSpinner color={color} />;
  }

  if (isError) {
    return <div>An error has occured.</div>;
  }

  dispatch(updateQuestions(createQuestions(data.results)));

  return (
    <>
      <Questions />
      {gameEnded ? <PlayAgainBtn /> : <VerifyButton />}
    </>
  );
}

export default Quiz;

This works fine but now, when the game is over, I have a "Play Again" button that's displayed and I'd like to add an on click to create a new fetch in order to get a new set of questions.这工作正常,但现在,当游戏结束时,我有一个显示的“再玩一次”按钮,我想添加一个点击以创建新的提取以获得一组新的问题。 I can't call the useFetch hook within a function like doing:我不能像这样在 function 中调用 useFetch 挂钩:

<button onClick={() => useFetch(newArgs)} />

so I tried to use mutate but I think because I am using the same url (the amount, category and difficulty doesn't change) when I call mutate, no new data is fetched所以我尝试使用mutate但我认为因为我在调用 mutate 时使用相同的 url(数量、类别和难度没有改变),所以没有获取新数据

You could try conditional fetching which has worked for me before.您可以尝试以前对我有用的条件提取 I can't remember if it invalidates the cache of SWR but I recall it being the correct answer over mutate .我不记得它是否使 SWR 的缓存无效,但我记得它是mutate的正确答案。 My thought is that when you select the "Play Again" button, you could have a state such as我的想法是,当您 select 按下“再玩一次”按钮时,您可能会有一个 state,例如

const [playAgain, setPlayAgain] = useState(false)

This gets passed to useFetch and you can structure useSWR like so:这将传递给useFetch ,您可以像这样构造 useSWR:

const { data, error } = useSWR(playAgain ? url : null, fetcher, {
    revalidateOnFocus: false,
  });

You'll need to come up with a solution for the first playthrough but that very well could be another state to handle that.您需要为第一个游戏想出一个解决方案,但这很可能是另一个 state 来处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM