乐闻世界logo
搜索文章和话题

How to call useQuery hook conditionally?

1个答案

1

The useQuery hook in React Query is a powerful tool that enables you to fetch, cache, and update data from asynchronous resources such as APIs. Sometimes, you may want to call useQuery only when specific conditions are met to avoid unnecessary network requests or ensure that all necessary dependencies are ready.

To conditionally invoke useQuery, utilize the enabled option. This option accepts a boolean value; when it is false, useQuery does not run automatically. You can set this boolean value based on any logic, such as checking if a variable exists or if a state has a specific value.

Here is an example using the enabled option:

jsx
import { useState } from 'react'; import { useQuery } from 'react-query'; const fetchProjectDetails = async (projectId) => { const response = await fetch(`/api/projects/${projectId}`); if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }; function MyComponent() { const [selectedProjectId, setSelectedProjectId] = useState(null); const { data, error, isLoading } = useQuery( ['projectDetails', selectedProjectId], () => fetchProjectDetails(selectedProjectId), { // useQuery will only run when selectedProjectId is truthy enabled: !!selectedProjectId, } ); // ... UI logic and rendering ... if (isLoading) return 'Loading...'; if (error) return 'An error has occurred: ' + error.message; return ( // Render project details or a project selection interface ); }

In this example, useQuery will only load the project details when selectedProjectId has a valid value. Initially, selectedProjectId is null, so useQuery does not perform data loading until the user selects a project and selectedProjectId is set to a truthy value.

This approach effectively ensures that your component fetches data as expected without initiating network requests when unnecessary, which can improve application performance and avoid potential errors.

2024年6月29日 12:07 回复

你的答案