Member-only story

Call API based on other API response — React Query

Vinodh Thangavel
2 min readJul 5, 2023

--

React query is one of most useful react libraries with lot of useful features, lets call TODOS API and extract the user_id from the response, make USER API call to get user details

export default function App() {

const { isLoading: todoIsLoading, data: todo } = useQuery('todo', () =>
fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) =>
response.json()
)
);

const userId = todo?.userId;

const { isLoading: userIsLoading, data: user } = useQuery(
['user', userId],
() =>
fetch('https://jsonplaceholder.typicode.com/users/' + userId).then(
(response) => response.json()
),
{enabled:!!userId}
);

if (todoIsLoading || userIsLoading) {
return <p> Loading ... </p>;
}

return (
<div>
<h1>Todo - {todo?.title} </h1>
<h2> User - {user?.name}</h2>
</div>
);
}

Code Analysis

  • useQuery hook is used to make the API call (React-query basic usage) , first we are making todos call, the response is destructed and renamed (JS destructuring cheatsheet) as we are making two useQuery in same block scope
  • The todo response is parsed and userId is extracted. Optional Chaining ? is mandatory here, as when the API call is being made, isLoading is true and data is undefined , so to avoid breaking the code (JS Most frequent Errors)
  • useQuery is used again, but this queryKey is not a string like todo, it is an array, because we need to pass an…

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet