Day 8 #100DaysOfCode 💻 Today I learned how to add a loading spinner before fetching API data. When we fetch data from an API, it may take some time. To improve user experience, we can show a loading spinner while the data is loading and hide it after the data is received. Simple example: function showLoading(){ document.getElementById("spinner").classList.remove("hidden"); } function hideLoading(){ document.getElementById("spinner").classList.add("hidden"); } showLoading(); fetch("https://lnkd.in/gAwJs9UG") .then(res => res.json()) .then(data => { console.log(data); hideLoading(); }) .catch(error => { console.log(error); hideLoading(); }); Small improvement, but it makes the UI feel much more professional. #100DaysOfCode #JavaScript #WebDevelopment #FrontendDevelopment #API #LearningInPublic #Akbiplob
Adding a Loading Spinner to Improve User Experience
More Relevant Posts
-
Stop using `index` as a key in your React lists just to make the console warning go away. You aren't actually fixing the problem. You are just hiding a potential production bug. React uses the `key` prop as the "source of truth" to track which elements changed, moved, or were deleted during its reconciliation process. It is the unique identity of your component in the virtual DOM. When you use the array index as a key, you are telling React that the "first" item is always the same component instance, regardless of the data it actually holds. This works fine for static lists that never change. But the moment you sort, filter, or remove an item, your UI can go out of sync with your data. If your list item has any internal state, such as an input value or a toggle, that state is tied to the index. If you delete the first item in a list of three, the new first item (which was originally second) will suddenly inherit the state of the deleted item. This happens because React sees that "Key 0" still exists and assumes it can reuse the existing component instance to save on performance. Instead of a simple move, you get a state mismatch that is incredibly hard to debug. It turns your predictable UI into a series of side effects that depend on the order of your array rather than the data itself. The rule is simple. Always use a stable, unique ID from your data. Whether it is a UUID or a database primary key, a stable identity ensures that your renders remain predictable and your component state stays exactly where it belongs. #ReactJS #SoftwareEngineering #WebDevelopment #CodingTips #Javascript #FrontendArchitecture
To view or add a comment, sign in
-
Today I was exploring how we fetch API data in React applications. In many cases, when we fetch data directly inside components, each component makes its own API call. This made me think for a moment. If multiple components need the same data, does that mean we have to fetch the same API again and again? 🤔 That approach can lead to: • repeated API calls • unnecessary network requests • harder state management So I started looking for a better way to handle shared data across the application. That’s where Redux becomes very useful. Redux allows us to store application data in a centralized global store. Instead of fetching the same data in multiple components, we can fetch it once and store it in the Redux store. Any component in the application can then access that data from the store. Benefits: • centralized state management • avoids repeated API calls • predictable data flow • easier debugging In simple terms: Component-based fetching → data scattered across components Redux store → data managed in one place It was interesting to see how tools like Redux help maintain cleaner architecture in larger applications. #ReactJS #Redux #FrontendDeveloper #WebDevelopment #JavaScript #NextJS
To view or add a comment, sign in
-
-
Thanks to Ignacio Casale for ideas on libraries for charts for React. Today I adapted an 'EChart' chart to use in React dashboard, intially fetching data using Tanstack (React) Query instead of the JQuery examples in the documentation (looking at how it will be kept in sync with the database later on in the project). Read around it found some fantastically useful articles. There were wrapper libraries produced for react for it in 2022, I'm curious to know, does anyone have anything more current that is still maintained (and likely to be in future if you have a crystal ball?!) to recommend please? I just wrote my own wrapper after reading around it but it would be really useful to know.
To view or add a comment, sign in
-
-
This pattern is everywhere: useEffect(() => { setLoading(true); fetch('/api/data') .then(r => r.json()) .then(setData) .catch(setError) .finally(() => setLoading(false)); }, []); Problems: ❌ No caching ❌ Race conditions ❌ Manual loading/error state ❌ No background refetch ❌ Stale data on re-focus Use TanStack Query: const { data, isLoading } = useQuery({ queryKey: ['data'], queryFn: fetchData }); All problems solved. Your future self will thank you. #ReactNative #JavaScript #CleanCode #ReactQuery #MobileDev
To view or add a comment, sign in
-
Day 98 of me reading random and basic but important dev topicsss.... Today I read about the abort request in fetch..... By default, JavaScript Promises don't have a built-in "cancel" button. Once a fetch() is fired, it wants to run to completion, which can eat up bandwidth, cause memory leaks, or create race conditions in your UI if the data arrives after the user has moved on. Enter the native Web API superhero: AbortController.... Here's how it works under the hood: An AbortController is a simple object with a single method (abort()) and a single property (signal). When you call controller.abort(), the signal object emits an "abort" event, and its aborted property becomes true. Because modern fetch is designed to integrate seamlessly with this API, it actively listens for that exact signal! Here is the standard recipe: 1. Create a new controller instance. 2. Pass its signal as an option to your fetch. 3. Call controller.abort() when the request is no longer needed (e.g. component unmounts, user hits a "Cancel" button, or a timeout is reached). the implementation: // 1. Initialize the controller const controller = new AbortController(); // Let's set a timeout to cancel the request after 1 second setTimeout(() => controller.abort(), 1000); try { // 2. Pass the signal to fetch const response = await fetch('/api/heavy-data', { signal: controller.signal }); console.log("Data loaded!", await response.json()); } catch (err) { // 3. Handle the AbortError specifically if (err.name === 'AbortError') { console.log(" Request was successfully aborted!"); } else { console.error("Fetch failed:", err); } } Note- Always handle that AbortError in your catch block! When fetch aborts, it intentionally rejects the promise. Catching it specifically ensures it doesn't get logged as a false positive in your error tracking software (like Sentry or Datadog). Keep Learning!!!! #JavaScript #WebDevelopment #FrontendEngineering #SoftwareDevelopment #FetchAPI
To view or add a comment, sign in
-
-
I stopped using useEffect for data fetching. Here's why. For years, my React components looked like this: useEffect(() => { setLoading(true); fetch('/api/users') .then(res => res.json()) .then(data => setUsers(data)) .catch(err => setError(err)) .finally(() => setLoading(false)); }, []); Loading state. Error state. Race conditions. Cleanup functions. Stale closures. Every. Single. Component. Then I switched to React Query (TanStack Query) and deleted 40% of my state management code overnight. Here's what changed: → No more loading/error/data useState triplets → Automatic caching — same data across 10 components, 1 network request → Background refetching — users always see fresh data without spinners → Race condition handling — built in, not bolted on → Retry logic — automatic, configurable, zero custom code But here's what most tutorials won't tell you: React Query doesn't replace ALL useEffect calls. It replaces the ones you should never have written in the first place. useEffect is still perfect for: • Subscriptions (WebSocket, event listeners) • DOM synchronization • Third-party library integration The mistake is using useEffect as a "fetch on mount" hook. That was always a workaround, not a pattern. In my TypeScript projects, I enforce this with a simple ESLint rule: no fetch() inside useEffect. If you're fetching data, use a query hook. Period. The result? Components that are 50% shorter, easier to test, and actually work correctly with React 18+ concurrent features. What's your go-to data fetching approach in React? Still useEffect, or have you moved on? #React #TypeScript #ReactQuery #TanStackQuery #WebDevelopment #JavaScript #DeveloperProductivity #CleanCode
To view or add a comment, sign in
-
-
Took the fetch and async/await practice further: built a small weather app that talks to a real API. What I did: A getWeather(location) function that calls the Visual Crossing timeline API, awaits the response, parses JSON, and (for now) logs the data. Location goes in the URL; the API key lives in a query parameter. Straightforward once you remember to await both the fetch and the .json() call. What I learned: The response is a big object — resolvedAddress, description, days[], currentConditions. To pull out one field I used dot notation: data.currentConditions.cloudcover. First try I wrote data.currentConditions[cloudcover] and got a ReferenceError: bracket notation expects a variable or a string, so JavaScript was looking for a variable named cloudcover that didn’t exist. Small gotcha, big “aha.” Next: Hook this up to the UI and display the data. One step at a time. If you’re past “fetch in the console” and want a concrete project, a weather app is a nice next step — one function, one API, and a clear path to putting data on the page. #JavaScript #LearningInPublic #APIs
To view or add a comment, sign in
-
-
Day 92 of me reading random and basic but important dev topicsss..... Today I read about the modern Fetch API.... If you are still reaching for XMLHttpRequest or unnecessarily bundling heavy external libraries for simple network calls, it's time to leverage the native power of fetch(). It’s modern, versatile, and built directly into all modern browsers. Here is everything every dev need to know about the anatomy of a Fetch request. 1. The Two-Stage Process Getting a response with fetch() isn't a single step; it’s a two-stage promise resolution: Stage 1: The Headers Arrive The promise returned by fetch(url) resolves with a Response object the moment the server responds with headers - before the full body downloads. This is where you check the HTTP status. Note: A 404 or 500 error does NOT reject the promise. A fetch promise only rejects on network failures. Always check response.ok (returns true for 200-299 statuses) or response.status! Stage 2: Reading the Body To actually get the data, you need to call an additional promise-based method on the response. Fetch gives you multiple ways to parse the body: * response.json() - parses as JSON (most common) * response.text() - returns raw text * response.blob() - for binary data with types (like downloading an image) * response.formData() - for multipart/form-data * response.arrayBuffer() - for low-level binary data 2. The Already Consumed Trap Here is a classic gotcha that trips up many developers: We can only read the body once. If we call await response.text() to debug or log the output, and then subsequently call await response.json(), your code will fail. The stream has already been consumed! Summary of a standard GET request: let response = await fetch('https://lnkd.in/e4utYKVK'); if (response.ok) { let data = await response.json(); console.log(data); } else { console.error("HTTP-Error: " + response.status); } Keep Learning!!!! #JavaScript #WebDevelopment #SoftwareEngineering #FetchAPI #FrontendDev
To view or add a comment, sign in
-
-
I got tired of debugging API issues with console.log(). After one too many late nights staring at: POST /api/orders 500 8ms ...with zero context about what was in the request body, what the response said, or which user triggered it — I built something better. Introducing reqlog — a live HTTP request dashboard for NestJS, Express and Fastify. Drop it in as middleware and a dashboard opens at localhost:9000 showing every request in real time: → Full request + response body → Payload diff between requests → One-click request replay → Slow request highlighting → Zero config, zero persistence NestJS setup is literally 3 lines: import { ReqlogModule } from 'reqlog-nestjs' @Module({ imports: [ReqlogModule.forRoot()] }) // dashboard opens automatically I use this daily at Softylines across 45+ microservices. It replaced a debugging workflow that was costing my team hours every week. MIT licensed. Open source. Free forever. GitHub → https://lnkd.in/dzXM6BrK If you've ever added a console.log at 11pm in frustration — this one's for you. ⭐ #nodejs #nestjs #opensource #javascript #devtools #webdev
To view or add a comment, sign in
-
-
🚀 Understanding Node.js Event Loop: setTimeout vs setImmediate Ever noticed this behavior? 👇 𝙨𝙚𝙩𝙏𝙞𝙢𝙚𝙤𝙪𝙩(() => 𝙘𝙤𝙣𝙨𝙤𝙡𝙚.𝙡𝙤𝙜("𝙨𝙚𝙩𝙏𝙞𝙢𝙚𝙤𝙪𝙩"), 0); 𝙨𝙚𝙩𝙄𝙢𝙢𝙚𝙙𝙞𝙖𝙩𝙚(() => 𝙘𝙤𝙣𝙨𝙤𝙡𝙚.𝙡𝙤𝙜("𝙨𝙚𝙩𝙄𝙢𝙢𝙚𝙙𝙞𝙖𝙩𝙚")); 👉 Output: 𝘴𝘦𝘵𝘐𝘮𝘮𝘦𝘥𝘪𝘢𝘵𝘦 𝘴𝘦𝘵𝘛𝘪𝘮𝘦𝘰𝘶𝘵 𝘉𝘶𝘵 𝘵𝘩𝘦𝘯: 𝙘𝙤𝙣𝙨𝙤𝙡𝙚.𝙡𝙤𝙜("𝙃𝙚𝙡𝙡𝙤 𝙛𝙧𝙤𝙢 𝙘𝙤𝙣𝙨𝙤𝙡𝙚"); 𝙨𝙚𝙩𝙏𝙞𝙢𝙚𝙤𝙪𝙩(() => 𝙘𝙤𝙣𝙨𝙤𝙡𝙚.𝙡𝙤𝙜("𝙨𝙚𝙩𝙏𝙞𝙢𝙚𝙤𝙪𝙩"), 0); 𝙨𝙚𝙩𝙄𝙢𝙢𝙚𝙙𝙞𝙖𝙩𝙚(() => 𝙘𝙤𝙣𝙨𝙤𝙡𝙚.𝙡𝙤𝙜("𝙨𝙚𝙩𝙄𝙢𝙢𝙚𝙙𝙞𝙖𝙩𝙚")); 👉 Output: 𝘏𝘦𝘭𝘭𝘰 𝘧𝘳𝘰𝘮 𝘤𝘰𝘯𝘴𝘰𝘭𝘦 𝘴𝘦𝘵𝘛𝘪𝘮𝘦𝘰𝘶𝘵 𝘴𝘦𝘵𝘐𝘮𝘮𝘦𝘥𝘪𝘢𝘵𝘦 🤯 Why does this happen? It all comes down to how the Node.js Event Loop works: 🔸 setTimeout(fn, 0) → Executes in the Timers phase 🔸 setImmediate(fn) → Executes in the Check phase The execution order depends on where the code is running: ✅ In the main script → order is not guaranteed ✅ Inside I/O callbacks → setImmediate usually runs first 💡 Key takeaway: "0ms" doesn’t mean immediate — it just means "run in the next timers phase." If you're working with async code, understanding these subtle differences can save you from tricky bugs and unpredictable behavior. 📖 Deep dive: https://lnkd.in/eAuPiWB7 Thanks to Hitesh Choudhary Piyush Garg Chai Aur Code Anirudh J. #NodeJS #JavaScript #WebDevelopment #Backend #EventLoop #AsyncProgramming #Developers
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