⚛️ That moment when I finally got my API call to work… and data appeared on the screen! 😍 When I first started learning React, I thought fetching data was simple — just call the API and show the data. But then… the re-renders, async calls, and errors started showing up like plot twists 😅 That’s when I learned the right way 👇 ✅ Using useEffect() for API calls: import React, { useEffect, useState } from "react"; function UserList() { const [users, setUsers] = useState([]); useEffect(() => { fetch("https://lnkd.in/gTcasaiP") .then(res => res.json()) .then(data => setUsers(data)) .catch(err => console.error(err)); }, []); return ( <ul> {users.map(user => <li key={user.id}>{user.name}</li>)} </ul> ); } 💡 Lesson learned: Always use useEffect() for API calls to avoid infinite loops. Handle loading and errors gracefully. Keep your data state clean and predictable. Once I understood this pattern, fetching data in React felt like second nature. ⚡ #ReactJS #WebDevelopment #FrontendDeveloper #MERNStack #JavaScript #API #useEffect #ReactHooks #LearningByDoing #CodingJourney
How to fetch data in React with useEffect()
More Relevant Posts
-
💡 Frontend Dev Trick: Another way to get what you want — with a bit of flatMap magic! You know those APIs that love to send back data inside data, wrapped in an array, sitting next to a meta or something like that? It’s like opening a gift box just to find another box inside it. 🎁 Something like this: [ { "data": [ { /* your items */ } ], "meta": { /* pagination info */ } } ] Most of us just go: const items = response[0].data; And hey — that works! 👏 No one’s judging. But sometimes, when you’re juggling multiple pages of results or working with React Query’s useInfiniteQuery, there’s a smoother move. Enter our elegant little friend: flatMap. ⚛️ When React Query Meets flatMap When you use useInfiniteQuery, your data usually looks like a stack of pages. Here’s the classic way: const posts = data.pages.map(page => page.data).flat(); Now, with flatMap, it’s like telling JavaScript: “Yeah, do both things at once, buddy.” const posts = data.pages.flatMap(page => page.data); One line. Elegant. Easy to read. Less typing — more sipping your coffee ☕. 💬 When do I use it? Whenever I’m transforming paginated API responses or reshaping data to fit existing component props — especially with infinite scrolls. It’s not the only way, but it’s a neat one-liner that keeps your code looking sharp. So next time you’re wrangling paginated data, maybe give flatMap a try — not because you have to, but because it feels… satisfying. 😎 What about you? Got your own tricks for flattening or shaping API responses? Drop them below — let’s trade a few elegant hacks! 💬 #frontend #reactjs #reactquery #javascript #webdev #cleancode #developerlife #codingtips Just dont forget about optional chaining bro... 😅
To view or add a comment, sign in
-
-
🔁 State Lifting in React | The Smart Way to Share Data Between Components. Ever had two React components that needed to share the same data, but didn’t know how? 🤔 That’s where the concept of State Lifting comes in, one of React’s most elegant patterns. 🧩 What Is State Lifting? When two or more components need access to the same data, you lift that state up to their closest common parent. The parent manages the data, and the children receive it through props. This keeps data centralized and consistent. 🧠 Let’s See an Example. Now look the example code below, let’s say we have two child components one to input data, and one to display it. Without lifting state, they can’t “talk” to each other directly. 🧭 Here, both child components share the same state managed by their parent. 🚀That’s state lifting in action. 🧠 Best Practice Lift state only when needed, not every piece of state should live in the parent. If many components need the same state → consider React Context. Keep the flow of data unidirectional (top → down). 💬 Final Thought: State lifting teaches one of React’s golden rules. 👉 Share state by moving it up, not across. #ReactJS #MERNStack #FrontendDevelopment #WebDevelopment #ReactPatterns #ReactHooks #JavaScript #CleanCode #LearnReact #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗲𝗲𝗽 𝗗𝗶𝘃𝗲: 𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝘁𝗵𝗲 𝗙𝗲𝘁𝗰𝗵 𝗔𝗣𝗜 💡 Say goodbye to old-school XMLHttpRequest! The Fetch API is the modern, promise-based way to make HTTP requests in JavaScript — simple, powerful, and elegant. ⚡ 🔹 𝗕𝗮𝘀𝗶𝗰 𝗙𝗲𝘁𝗰𝗵 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: fetch('https://lnkd.in/gWKpgMrT') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ✅ fetch() returns a Promise ✅ response.json() converts response to JSON ✅ .catch() ensures error handling 🔹 𝗖𝗹𝗲𝗮𝗻𝗲𝗿 𝗦𝘆𝗻𝘁𝗮𝘅 𝘄𝗶𝘁𝗵 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁: async function getData() { try { const response = await fetch('https://lnkd.in/gWKpgMrT'); const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } getData(); ✨ No more nested .then() chains — just clean, readable async code! 💡 𝗣𝗿𝗼 𝗧𝗶𝗽𝘀: 🔸 Always handle network errors 🔸 Add headers for authentication & content-type 🔸 Supports GET, POST, PUT, DELETE and more Credit 💳 🫡 Sameer Basha Shaik 🚀 The Fetch API is a must-know tool for every frontend developer — perfect for fetching data, integrating APIs, and building modern web applications! 🌐 #JavaScript #FetchAPI #WebDevelopment #AsyncAwait #Frontend #CodingTips #CleanCode #DeveloperCommunity #Promises #LearnToCode #jsdeveloper
To view or add a comment, sign in
-
Working with tables in React ? Then you’ve got to check out React Data Table Component (RDT) one of the most powerful and easy-to-use libraries out there! ⚛️ It comes packed with built-in features like : ✨ Pagination ✨ Sorting ✨ Loading indicators ✨ Selectable Rows ✨ Expandable Rows But keep in mind these features work best for client-side data . If your data comes from an API or you’re dealing with large datasets, you’ll need to implement server-side pagination manually. Still, RDT makes building clean, responsive, and data-rich UIs a breeze! 🚀 For more details checkout their official docs : https://lnkd.in/d2pvECmu #React #JavaScript #FrontendEngineer #ReactDataTable #SoftwareDevelopment #KeepExploring
To view or add a comment, sign in
-
-
🚀 Mastering res.on() Events in Node.js – The Hidden Power Behind Streams! Ever wondered how you can listen to the lifecycle of an HTTP response in Node.js? That’s where res.on() comes in — it lets you react to key response events such as when data is being sent, finished, or when something goes wrong. Let’s break it down 👇 🧠 What is res.on()? In Node.js, every HTTP response object (res) is an EventEmitter, which means we can subscribe to events like: 'data' → when data chunks are being written 'end' → when all data is sent 'error' → when something goes wrong during transmission 'close' → when the connection closes (even abruptly) This gives developers fine-grained control over network responses — a must for performance monitoring, debugging, and logging. 💡 Why Use res.on()? ✅ Monitor outgoing responses — useful for logging and analytics. ✅ Handle premature disconnects — detect if clients drop off. ✅ Improve debugging — get detailed insights into request/response flow. ✅ Enhance performance tracking — measure when responses actually complete. 🎯 Key Takeaway res.on() turns your Node.js responses into observable events — empowering you to build robust, reliable, and production-grade servers with deeper control over network behavior. #NodeJS #BackendDevelopment #WebPerformance #FullStackDevelopment #JavaScript #LearningInPublic
To view or add a comment, sign in
-
-
Still confused about useEffect in React? Let’s clear it up once and for all! When I first started learning React, useEffect was one of those hooks that always felt tricky. When does it run? Why does it re-run? What’s the deal with the dependency array? After some deep practice and a lot of mistakes, I finally cracked how useEffect truly works, and I wrote a detailed, beginner-friendly tutorial to help others understand it too. In this post, I’ve explained: 1. What useEffect actually does 2. When and how it runs 3. How to use the cleanup function 4. Real examples for API fetching, timers, and more If you’re learning React or want to master hooks, this one’s for you. https://lnkd.in/d66KSm7V #React #ReactHooks #JavaScript #WebDevelopment #Frontend #CodingJourney
To view or add a comment, sign in
-
𝐓𝐨𝐝𝐚𝐲 𝐈 𝐥𝐞𝐯𝐞𝐥𝐞𝐝 𝐮𝐩 𝐦𝐲 𝐑𝐞𝐚𝐜𝐭 𝐬𝐤𝐢𝐥𝐥𝐬 𝐛𝐲 𝐢𝐦𝐩𝐥𝐞𝐦𝐞𝐧𝐭𝐢𝐧𝐠 𝐬𝐦𝐨𝐨𝐭𝐡, 𝐟𝐥𝐢𝐜𝐤𝐞𝐫-𝐟𝐫𝐞𝐞 𝐩𝐚𝐠𝐢𝐧𝐚𝐭𝐢𝐨𝐧 𝐮𝐬𝐢𝐧𝐠 𝐑𝐞𝐚𝐜𝐭 𝐐𝐮𝐞𝐫𝐲! I was exploring how to load API data page-by-page without the UI blinking or resetting and React Query’s 𝒌𝒆𝒆𝒑𝑷𝒓𝒆𝒗𝒊𝒐𝒖𝒔𝑫𝒂𝒕𝒂 feature completely changed the game for me. 🔥 What I Built - Dynamic Pagination using useState - Data Fetching with useQuery - Personalized API calls using pageNumber - Smooth transitions using keepPreviousData - Clean, minimal UI for posts + pagination buttons - Proper error & loading handling What I Learned 🔹 React Query refetches only when queryKey changes → ["posts", pageNumber] 🔹 queryFn should always be a function → () => FetchPosts(pageNumber) 🔹 API must receive the correct page number to return limited results 🔹 keepPreviousData helps avoid UI jumps and blank screens 🔹 Good CSS structure matters — it prevents overlapping and maintains layout 🎯 Outcome A smooth, modern, user-friendly pagination UI where: ✨ No flickering ✨ No layout shifting ✨ Old data stays visible while new data loads ✨ Perfect experience for users 🛠️ 𝑻𝒆𝒄𝒉 𝑺𝒕𝒂𝒄𝒌 : React.js, React Query, Axios, JSONPlaceholder API, Custom CSS I’m really enjoying diving deeper into React Query — the amount of control it gives over data fetching is incredible! Excited to keep building and learning more every day! #react #reactjs #reactquery #webdevelopment #frontenddeveloper #learningjourney #javascript
To view or add a comment, sign in
-
Error Handling in Async/Await (try...catch in JavaScript) When using Async/Await, handling errors properly is just as important as handling data. That’s where the try...catch block shines It helps you catch and manage errors without crashing your app. Definition: try — contains the code that may throw an error. catch — handles the error gracefully when something goes wrong. Example: function fetchData(success) { return new Promise((resolve, reject) => { setTimeout(() => { if (success) resolve("✅ Data fetched successfully"); else reject("❌ Failed to fetch data"); }, 1000); }); } async function getData() { try { console.log("Fetching data..."); const result = await fetchData(false); // change to true to test success console.log(result); } catch (error) { console.error("Error caught:", error); } finally { console.log("Operation completed ✅"); } } getData(); Output (if failed): Fetching data... Error caught: ❌ Failed to fetch data Operation completed ✅ ⚙️ Why it’s useful: ✅ Prevents app crashes ✅ Keeps async code clean ✅ Helps in debugging network/API issues ✅ Works beautifully with multiple awaits 🔖 #JavaScript #AsyncAwait #ErrorHandling #TryCatch #WebDevelopment #Frontend #CodingTips #AsyncProgramming #JSConcepts #100DaysOfCode #LearnsJS #DeveloperJourney #WebDevCommunity
To view or add a comment, sign in
-
🚀 Understanding Streams and Buffers in Node.js Have you ever wondered how Node.js efficiently handles large files like videos, logs, or data transfers without running out of memory? 🤔 The answer lies in Streams and Buffers — the backbone of Node.js I/O operations. A Buffer temporarily holds chunks of binary data, while a Stream processes that data piece by piece instead of loading everything at once. This approach makes Node.js incredibly efficient when dealing with big files or real-time data. Whether it’s reading a large CSV, serving a video, or handling file uploads, Streams help you process data continuously and save resources. Once you master Streams and Buffers, you can build scalable applications that handle massive data effortlessly. ⚡ 💭 Have you ever worked with file streams or HTTP streams in your Node.js projects? How was your experience? #NodeJS #JavaScript #BackendDevelopment #Streams #Buffers #Performance #WebDevelopment #Learning
To view or add a comment, sign in
-
🌟 Day 53 of JavaScript 🌟 🔹 Topic: Fetch API 📌 1. What is the Fetch API? The Fetch API allows JavaScript to make HTTP requests (like GET, POST, PUT, DELETE) to servers — used to retrieve or send data 🌐 💬 Think of it as JavaScript’s way to talk to web servers asynchronously. ⸻ 📌 2. Basic Syntax: fetch("https://lnkd.in/gXUzR2fM") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error:", error)); ✅ Step-by-step: 1️⃣ Fetch sends the request 2️⃣ Waits for the response 3️⃣ Converts it (like .json()) 4️⃣ Handles the data or errors ⸻ 📌 3. Using async/await: async function getData() { try { const response = await fetch("https://lnkd.in/gXUzR2fM"); const data = await response.json(); console.log(data); } catch (err) { console.error("Fetch failed:", err); } } getData(); ⚙️ Cleaner, more readable syntax for async operations. ⸻ 📌 4. POST Example: fetch("https://lnkd.in/gJ4WB7DB", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "Pavan", age: 25 }) }); ⸻ 📌 5. Why Use Fetch API? ✅ Simpler than XMLHttpRequest ✅ Promise-based ✅ Works with async/await ✅ Built-in for browsers ⸻ 💡 In short: The Fetch API makes calling APIs in JavaScript simple, powerful, and modern — the go-to tool for all web requests 🚀 #JavaScript #100DaysOfCode #FetchAPI #WebDevelopment #FrontendDevelopment #CodingJourney #JavaScriptLearning #CleanCode #AsyncJS #Promises #DevCommunity #CodeNewbie #WebDev
To view or add a comment, sign in
-
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