Most React developers fetch data like this: const user = await fetchUser() const posts = await fetchPosts() const stats = await fetchStats() Looks clean. Works fine. Until you realize each request waits for the previous one to finish. That is a waterfall. And it is quietly killing your dashboard load time. I ran into this building a dashboard at work. Three separate API calls running one after another. The page felt slow and I could not figure out why at first. The fix was simpler than I expected. Promise.allSettled runs all three requests at the same time. No waiting. No blocking. Everything fires in parallel and you get back all the results together, whether they succeeded or failed. The part most people miss is the error handling. Promise.all throws the moment one request fails and you lose everything. Promise.allSettled gives you the status of every single request so you can handle each one individually. Failed user fetch? Show a guest fallback. Failed stats? Show zeros. The rest of the page still loads. Attaching the code below. Steal it for your next dashboard. Are you still fetching data sequentially in your projects? #JavaScript #ReactJS #WebDevelopment #Frontend #Programming
Optimize React API Calls with Promise.allSettled
More Relevant Posts
-
I promised — and I delivered. Here's usePromise: a custom React hook I built that I genuinely believe should be in every developer's project from day one. Let me explain why. The problem nobody talks about openly: Every React developer has written this exact block of code hundreds of times mentioned in the image 👇 It works. It's familiar. And it's been silently violating the DRY principle across every codebase you've ever touched. usePromise replaces all of that with a single hook that handles: ✅ Loading, data, and error state — managed via useReducer to prevent async race conditions ✅ Real request cancellation via AbortController (not just ignoring the response — actually aborting the request) ✅ Data transformation at the configuration level with dataMapper ✅ Lifecycle callbacks — onSuccess, onError, onComplete, and isRequestAbortionComplete ✅ executeOnMount support — fire on render without a single useEffect in your component ✅ Full reset capability — return to initial state cleanly Why not just React Query? React Query is excellent for caching, deduplication, and large-scale data orchestration. But sometimes you want something you fully own — no black boxes, no magic, no dependency debates in code review. usePromise gives you that. It's a foundation you understand end-to-end and can extend however you need. Why should this be standard? SOLID principles tell us: don't repeat yourself. Async data fetching is the most repeated pattern in every React application in existence. The framework gives us the primitives — useReducer, useCallback, useEffect — but leaves the wiring entirely to us. Every team solves this problem. Most teams solve it inconsistently. This hook is the consistent answer. Three years in, and the thing I keep coming back to is this: the first few years of your career build the developer you'll be. The habits, the patterns, the defaults you reach for. Reach for clean ones. Full deep-dive article on Medium including the complete implementation, the Promise lifecycle explained from first principles, and an honest breakdown of trade-offs. This is the medium article for more clarity down below 👇 https://lnkd.in/gJWZhQXk #React #JavaScript #WebDevelopment #Frontend #OpenSource #ReactHooks #CleanCode
To view or add a comment, sign in
-
-
🚨 "async/await" makes asynchronous code look simple… But it’s also one of the easiest ways to introduce subtle bugs. Over the years, I’ve seen (and made) these mistakes more times than I’d like to admit. Here are some of the most common "async/await" mistakes that can cause real production issues 👇 💡 1. Forgetting to use "await" const data = fetch('/api/users'); // Promise, not actual data console.log(data); ✅ Correct: const data = await fetch('/api/users'); 💡 2. Using "await" inside loops unnecessarily for (const id of ids) { const user = await fetchUser(id); } This runs sequentially and can be painfully slow. ✅ Better: const users = await Promise.all(ids.map(fetchUser)); 💡 3. Missing error handling const data = await fetchData(); If the request fails, your app may crash. ✅ Always wrap critical async calls: try { const data = await fetchData(); } catch (error) { console.error(error); } 💡 4. Mixing ".then()" with "await" const data = await fetch(url).then(res => res.json()); It works, but it’s inconsistent and harder to read. ✅ Prefer one style: const res = await fetch(url); const data = await res.json(); 💡 5. Awaiting independent tasks one by one const user = await fetchUser(); const posts = await fetchPosts(); These can run in parallel. ✅ Better: const [user, posts] = await Promise.all([ fetchUser(), fetchPosts() ]); 💡 6. Not handling rejected promises in "Promise.all()" If one promise fails, the entire batch fails. 👉 Use "Promise.allSettled()" when partial success is acceptable. 🔥 "async/await" improves readability — but understanding how it behaves is what makes your code truly reliable. #JavaScript #JS #es6 #react #reactjs #AsyncAwait #WebDevelopment #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
Why Next.js? Because it does not let you take shortcuts. I just shipped DevEvents — a developer events platform built entirely with Next.js 16. Server Components force you to think about what runs on the server and what runs on the client. Suspense teaches you streaming. Dynamic routes teach you how URLs and databases connect. App Router teaches you how real applications are structured. You learn how web applications actually work. deploymentURL- https://lnkd.in/dkPmSTb6 GitHub- https://lnkd.in/d6mK5VMp Tech stack: Next.js 16+ TypeScript + React MongoDB + Mongoose Express + Mongoose with Node.js Cloudinary for image uploads Tailwind CSS + React Bits Vercel for deployment PostHog as Analytics Tool CodeRabbit for code review Postman for API testing Warp for AI integrated terminal What I learned with JavaScript Mastery : App Router — file based routing done the right way Server Components vs Client Components — what runs where and why it matters Server Actions — writing to the database directly from components Dynamic Routes — how URLs and databases connect through slugs Suspense & Streaming — showing UI before all data is ready Data Fetching Strategies — SSR, CSR, static generation and when to use each API Route Handlers — building backend APIs inside Next.js TypeScript Integration — type safety across the entire codebase Image Optimization — Next.js Image component and remote patterns Caching — use cache, no-store, revalidation and how they affect performance Metadata & SEO — making pages discoverable by search engines Clean Architecture — structuring a real production codebase Built it from scratch. Broke it constantly. Fixed every bug. Shipped it. That is the only I actually learn these days. . . . . . . . . . . . . . #NextJS #React #TypeScript #MongoDB #FullStack #WebDev #buildinpublic #developer #100DaysOfCode #chaiaurcode #chaicode #jsmastery #javascript #PostHog #warp #vscode #webdev #fullstckwebdev #developer #programming #coderabbit #AI #ai
To view or add a comment, sign in
-
-
I used to wonder why my Node.js server slowed to a crawl under load. Then I truly understood the event loop. 💡 Here's what changed — with real examples. 🔷 THE CORE IDEA Node.js runs on a single thread. But it handles thousands of concurrent operations without breaking a sweat. The secret? It never waits. When Node.js hits an async operation — a DB call, an API request, a file read — it hands it off to the system and keeps moving. The event loop picks up the result when it's ready and executes the callback. This is why Node.js excels at I/O-heavy workloads. 🔷 WHERE IT WINS IN THE REAL WORLD ✅ High-concurrency APIs Handling 10,000 simultaneous requests? Node.js doesn't spin up 10,000 threads. It processes each callback as responses arrive — lean and efficient. ✅ Real-time applications Chat apps, live notifications, collaborative tools — all powered by the event loop's ability to handle thousands of WebSocket connections without dedicated threads per user. ✅ Streaming data Video streaming, large file transfers — Node.js streams chunks of data through the event loop continuously, keeping memory usage low. 🔷 WHERE IT BREAKS — AND HOW TO FIX IT ❌ CPU-intensive tasks on the main thread Running image compression, PDF generation, or complex calculations synchronously blocks the event loop. Every other request waits. → Fix: Use worker_threads or offload to a background job queue. ❌ Deeply nested synchronous loops A for loop processing 1 million records on the main thread starves the event loop. → Fix: Break work into async chunks or use streams. ❌ Misunderstanding setTimeout() setTimeout(fn, 0) doesn't mean immediate. It means "after the current stack clears and when the event loop gets to it." → Fix: Use setImmediate() or process.nextTick() when execution order matters. 🔷 THE GOLDEN RULE The event loop is the heartbeat of your Node.js server. Every millisecond you block it, every user feels it. Write async code. Offload heavy work. Understand your phases. That's how you build Node.js apps that scale. 🚀 What's the most unexpected event loop issue you've debugged? I'd love to hear it 👇 #NodeJS #JavaScript #BackendDevelopment #EventLoop #WebPerformance #SoftwareEngineering #FullStackDevelopment #TechTips #AsyncProgramming #NodeJSDeveloper
To view or add a comment, sign in
-
⚙️ From a Single Click to a Complete System Flow 🎯 At first glance, it feels simple: 👉 Click → API → Data → UI ❌ Reality? Not even close. ⚙️ A single action flows through: 🧠 Frontend logic → 🌐 API call → 🛡️ Middleware → 🛣️ Routes → 🎯 Controller → 🧩 Service → 🗄️ Database → 📦 Response → 🔄 State → 🎨 Re-render 💡 Here’s the truth: If your logic lives only inside controllers, you’re setting yourself up for ⚠️ messy, unscalable code. 🧱 Good developers make it work. 🏗️ Great developers make it structured. #MERNStack #FullStackDeveloper #BackendDevelopment #WebDevelopment #ReactJS #NodeJS #ExpressJS #MongoDB #JavaScript #SoftwareEngineering #SystemDesign #CleanCode #APIDevelopment #BuildInPublic #DevCommunity
To view or add a comment, sign in
-
-
🚀 Day 17/30 – Custom Hooks (Deep Dive) Tired of repeating the same logic in multiple components? 🤔 Today I learned how to make React code reusable & clean ⚡ 👉 Custom Hooks Today I learned: ✅ Custom Hooks are reusable functions using React Hooks ✅ They help extract and reuse logic across components ✅ Must always start with "use" (naming convention) --- 💻 Problem: Same logic repeated in multiple components ❌ (e.g. fetching data, form handling) --- 💻 Solution: Create a custom hook ✅ --- 💻 Example: function useCounter() { const [count, setCount] = useState(0); const increment = () => setCount((prev) => prev + 1); const decrement = () => setCount((prev) => prev - 1); return { count, increment, decrement }; } function App() { const { count, increment, decrement } = useCounter(); return ( <> <h2>{count}</h2> <button onClick={increment}>+</button> <button onClick={decrement}>-</button> </> ); } --- 🔥 What actually happens: 1️⃣ Logic is written once inside custom hook 2️⃣ Any component can reuse it 3️⃣ Each component gets its own state --- 💡 Real Use Cases: - API fetching (useFetch) - Form handling (useForm) - Authentication logic - Debouncing input --- ⚡ Advanced Insight: Custom Hooks don’t share state ❌ 👉 They share logic, not data --- 🔥 Key Takeaway: Write logic once → reuse everywhere. Are you still repeating logic or using custom hooks? 👇 #React #CustomHooks #FrontendDevelopment #JavaScript #CleanCode
To view or add a comment, sign in
-
-
I got tired of the "Boilerplate Side Quest," so I built a tool to skip it. Every new project = same 20–30 min of setup (folders, Vite, Express, configs 😵💫) So I decided to fix it. I built "mern-cli-start" 📦 — a CLI tool that lets you go from an empty folder to a production-ready MERN project in seconds. ⚙️ What it sets up for you: ✅ Frontend: React + Vite (fast, modern setup) ✅ Backend: Node.js + Express with clean MVC architecture ✅ Database: Pre-configured MongoDB connection logic ✅ Project Structure: Scalable, organized, and ready for real development No more manual setup. No more copy-pasting boilerplate. Just run one command and start building what actually matters. 🚀 Try it out (no installation needed): npx mern-cli-start <project-name> Would love your feedback and suggestions! 🔗 NPM: https://lnkd.in/gu6qvvzR 💻 GitHub: https://lnkd.in/gZQAG8Vw #MERN #WebDevelopment #NodeJS #JavaScript #BuildInPublic #Automation #Developers #OpenSource
To view or add a comment, sign in
-
-
Most React devs think they understand useEffect. They don't. And it's costing them subtle bugs in prod. Here's the one thing nobody explains clearly: The cleanup function doesn't run when you think it does. Say you're fetching user data based on a userId prop: > the buggy version useEffect(() => { fetch(`/api/user/${userId}`) .then(res => res.json()) .then(data => setUser(data)); }, [userId]); Looks fine, right? It's not. If userId changes from 1 → 2 quickly, maybe the user is clicking through a list, both requests are in flight. Whichever resolves last wins. You could end up showing user 1's data on user 2's profile. That's a race condition, and it's completely silent. Here's how you fix it with an AbortController: > the correct version useEffect(() => { const controller = new AbortController(); fetch(`/api/user/${userId}`, { signal: controller.signal }) .then(res => res.json()) .then(data => setUser(data)) .catch(err => { if (err.name !== 'AbortError') throw err; }); return () => controller.abort(); }, [userId]); Now when userId changes, React runs the cleanup - which aborts the in-flight request, before firing the new effect. No stale data. No race. No mystery bug at 2am. The cleanup function is not just for "removing event listeners." It's your undo button for whatever the effect started. Timers? Clear them. Subscriptions? Unsubscribe. Requests? Abort them. I've seen this bite senior devs on dashboards, search inputs, and paginated lists more times than I can count. If your useEffect fetches data and has no cleanup, there's a bug waiting to happen. #React #MERN #WebDevelopment #JavaScript #FrontendDevelopment #ReactNative
To view or add a comment, sign in
-
🚀 Redux vs RxJS — Stop Confusing Them! A lot of developers (especially in Angular) mix up Redux and RxJS. I did too at one point 😅 Let’s simplify it 👇 🔹 Redux = State Management 🔹 RxJS = Asynchronous Data Handling 🧠 What is Redux? Think of Redux as a central store for your application. ✔️ Stores all your app data ✔️ Uses actions to describe changes ✔️ Uses reducers to update state 👉 Example: User clicks “Add to Cart” → Action → Reducer → Store updated 💡 It ensures your app state is predictable and easy to debug. ⚡ What is RxJS? RxJS is all about handling data streams asynchronously. ✔️ Observables (data streams) ✔️ Operators (map, filter, debounce) ✔️ Subscriptions (listen to data) 👉 Example: API calls User typing (search suggestions) Real-time updates 💡 It helps you react to events over time. 🔥 Key Difference Redux → Where data is stored RxJS → How data flows 🧩 How They Work Together In real Angular apps: 1️⃣ RxJS fetches data (API call) 2️⃣ Dispatch action 3️⃣ Redux updates state 4️⃣ UI updates automatically 💡 Simple Analogy Redux = 🗄️ Database RxJS = 🚰 Data pipeline ⚠️ Common Mistake “RxJS can replace Redux” ❌ 👉 RxJS handles data flow 👉 Redux manages state ✨ When to Use What? ✔️ Use Redux → Complex shared state ✔️ Use RxJS → Async operations & events If you're learning Angular, mastering both is a game-changer 💪 #Angular #Frontend #WebDevelopment #RxJS #Redux #NgRx #JavaScript #SoftwareEngineering
To view or add a comment, sign in
-
-
Stop treating Inertia.js like a standard SPA. It’s killing your scalability. 🔄 After 10 years in the Laravel and Vue.js ecosystem, I’ve realized that the "magic" of Inertia is where most architectural debt actually begins. It’s incredibly easy to get started, but when you scale to thousands of simultaneous users, your middleware choices matter more than your framework features. The most common architectural failure I see? Treating the HandleInertiaRequests middleware like a global dumping ground for shared data. The "Senior" approach requires looking deeper into the stack: Shared Data Bottlenecks: If you aren't aggressively using Lazy Props (Inertia::lazy) for heavy datasets or user-specific context, you are adding unnecessary overhead to every single request. You’re effectively DDoS-ing your own API with every page visit. State Management: Real optimization is knowing exactly when a heavy computation belongs in a Laravel Resource (server-side) vs. a Vue computed property (client-side) to keep the browser's main thread free for interaction. The "Silent" Failures: It’s about utilizing Partial Reloads properly and implementing Manual Visit Cancellations to prevent UI race conditions when users click faster than your server can respond. I’ve found that building for the "happy path" is easy. Building for the "scale path" is where the real engineering happens. Fellow Laravel/Vue devs: How are you handling massive shared data payloads in Inertia? Are you a fan of Lazy Props, or do you prefer keeping the middleware lean and using XHR for the heavy lifting? 👇 #Laravel #VueJS #InertiaJS #FullStackArchitecture #WebPerformance #SoftwareEngineering #PHP #WebDev
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Spent way too long debugging a slow dashboard before I found this. Hope it saves someone a few hours.