CodexBloom - Programming Q&A Platform

React 18: Handling Multiple Async Data Fetches and Their Order of Execution

๐Ÿ‘€ Views: 367 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-14
reactjs async-await useEffect javascript

Can someone help me understand I'm currently working on a React 18 application where I need to fetch data from multiple APIs sequentially... The first API call retrieves user details, and based on that, a second call fetches user-specific settings. However, Iโ€™m working with a situation where the second call sometimes executes before the first one completes, which leads to errors in processing the fetched data. Iโ€™m using `useEffect` for the data fetching logic. Hereโ€™s a simplified version of my code: ```javascript import React, { useEffect, useState } from 'react'; const UserProfile = () => { const [user, setUser] = useState(null); const [settings, setSettings] = useState(null); useEffect(() => { const fetchData = async () => { try { const userResponse = await fetch('https://api.example.com/user'); const userData = await userResponse.json(); setUser(userData); // This call is dependent on the first one const settingsResponse = await fetch(`https://api.example.com/settings/${userData.id}`); const settingsData = await settingsResponse.json(); setSettings(settingsData); } catch (behavior) { console.behavior('behavior fetching data:', behavior); } }; fetchData(); }, []); if (!user || !settings) return <div>Loading...</div>; return <div>User: {user.name}, Settings: {settings.theme}</div>; }; export default UserProfile; ``` Despite using `async/await`, I sometimes see the behavior `TypeError: want to read properties of null (reading 'id')` because the second fetch is trying to access `userData.id` before the first fetch completes. Iโ€™ve also considered using a state management library, but Iโ€™d like to keep it simple for now. Has anyone faced a similar scenario, and how can I ensure that the second API call only executes after the first one has fully resolved? Any best practices or alternative patterns would be greatly appreciated! I'm using Javascript latest in this project.