CodexBloom - Programming Q&A Platform

React 18: Handling Multiple API Calls in useEffect with Race Condition Issues

👀 Views: 46 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
reactjs useEffect api JavaScript

I'm relatively new to this, so bear with me..... I keep running into I'm updating my dependencies and I'm trying to configure I'm working on a React 18 application where I have a component that makes two API calls in a single `useEffect`... The goal is to fetch user data and user preferences simultaneously. However, I'm working with issues with race conditions, resulting in either state getting overwritten or unexpected data being displayed. Here's what my code looks like: ```javascript import React, { useEffect, useState } from 'react'; const UserProfile = () => { const [userData, setUserData] = useState(null); const [userPreferences, setUserPreferences] = useState(null); useEffect(() => { const fetchUserData = async () => { const response = await fetch('/api/user'); const data = await response.json(); setUserData(data); }; const fetchUserPreferences = async () => { const response = await fetch('/api/preferences'); const data = await response.json(); setUserPreferences(data); }; fetchUserData(); fetchUserPreferences(); }, []); if (!userData || !userPreferences) { return <div>Loading...</div>; } return ( <div> <h1>{userData.name}</h1> <p>{userPreferences.theme}</p> </div> ); }; export default UserProfile; ``` After implementing this, I've noticed that if the user data loads faster than the preferences, the component sometimes displays stale or incorrect theme information. Sometimes, it even throws an behavior: `want to read property 'theme' of null`. I tried handling this by adding loading states for both API calls, but it hasn't resolved the race condition. Is there a recommended approach to manage these API calls without running into such issues? Should I consider using `Promise.all` or maybe refactoring this logic in some way? Any suggestions or examples would be greatly appreciated! This is part of a larger CLI tool I'm building. Any ideas what could be causing this? I'm on Windows 11 using the latest version of Javascript. What's the correct way to implement this? I'm working with Javascript in a Docker container on Debian. I'm on Ubuntu 20.04 using the latest version of Javascript. I'm open to any suggestions. I'm coming from a different tech stack and learning Javascript. Is there a better approach?