I have a component that fetches a bunch of posts. This has a set of filters too.
const [selectedCountry, setSelectedCountry] = useState(null);
const [selectedStatus, setSelectedStatus] = useState(null);
const getPosts = async (payload) => {
const response = await fetchPosts(payload);
return response;
};
const payload = {
country: selectedCountry,
status: selectedStatus,
};
const {isLoading, data: posts} = useQuery(['posts', payload], () => getPosts(payload));
const handleApplyFilters = () => {
// refecth the posts with the applied filter payload
}
return (
<>
<select
name="countryFilter"
value={selectedCountry}
onChange={(e) => {
setSelectedCountry(e.target.value);
}}>
<option>Singapore</option>
<option>Finland</option>
<option>Portugal</option>
</select>
<select
name="statusFilter"
value={selectedStatus}
onChange={(e) => {
setSelectedStatus(e.target.value);
}}>
<option>Online</option>
<option>Offline</option>
<option>Blocked</option>
</select>
<button onClick={handleApplyFilters}>
Apply Filters
</button>
{posts.map((post) => (
<div>
<div>{post.title}</div>
<div>{post.description}</div>
</div>
))}
</>
)
I'm not sure how to achieve the following using react-query.
- fetch posts only during the initial render
- Avoid fetching posts on every filter change (only re-fetch when the
Apply Filterbutton is clicked)