Slide 24
Slide 24 text
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
async function fetchPosts({ queryKey }) {
const [_key, { startDate, endDate }] = queryKey;
const params = new URLSearchParams({ startDate, endDate }).toString();
const res = await fetch(`https://api.example.com/posts?${params}`);
return res.json();
}
export default function Posts() {
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
// ⭐ React Query が自動でフェッチ & リフェッチしてくれる
const { data, isLoading, error } = useQuery({
queryKey: ["posts", { startDate, endDate }],
queryFn: fetchPosts,
enabled: Boolean(startDate && endDate), // 両方入力されたときだけ実行
});
...
}
データフェッチを全て ReactQueryが
管理してくれるためエフェクトどころ
かstateも不要