Autocomplete API Calls and Caching
How to fetch suggestions from an API and cache results for performance.
Autocomplete API Calls and Caching
Fetching suggestions from an API and caching results improves performance. Here is how.
Fetching from an API
async function fetchSuggestions(query) { const response = await fetch(`/api/suggestions?q=${encodeURIComponent(query)}`); const data = await response.json(); return data; }
Caching Results
const cache = new Map(); async function fetchWithCache(query) { if (cache.has(query)) { return cache.get(query); } const data = await fetchSuggestions(query); cache.set(query, data); return data; }
Cache with Expiration
const CACHE_TTL = 60000; // 1 minute function fetchWithExpiringCache(query) { if (cache.has(query)) { const { data, timestamp } = cache.get(query); if (Date.now() - timestamp < CACHE_TTL) return data; } const data = await fetchSuggestions(query); cache.set(query, { data, timestamp: Date.now() }); return data; }
Cancel Previous Requests
let currentController; async function fetchWithCancellation(query) { if (currentController) currentController.abort(); currentController = new AbortController(); try { const res = await fetch(`/api/suggestions?q=${query}`, { signal: currentController.signal }); return await res.json(); } catch (err) { if (err.name !== "AbortError") throw err; } }
The Takeaway
API calls and caching: fetch from API (with encodeURIComponent), cache results (Map with query as key), cache with expiration (TTL), and cancel previous requests (AbortController). Caching avoids duplicate API calls for the same query. Cancellation prevents race conditions when the user types quickly.
Use fetch: const res = await fetch(`/api/suggestions?q=${encodeURIComponent(query)}`); return await res.json(). Always encode the query with encodeURIComponent to handle special characters.
Use a Map: if cache.has(query) return cache.get(query); otherwise fetch, then cache.set(query, data). This avoids duplicate API calls for the same query, improving performance and reducing server load.
Use AbortController: before each fetch, abort the previous controller and create a new one. Pass the signal to fetch. If the user types quickly, only the last request completes; previous ones are aborted.
To prevent race conditions. If the user types 'hello', 5 requests may be in flight. The 'h' response might arrive after 'he', overwriting the correct results. Cancelling previous requests ensures only the latest query's response is used.
Store { data, timestamp } in the cache. On lookup, check if Date.now() - timestamp < CACHE_TTL. If the entry is too old, fetch fresh data and update the cache. This prevents stale suggestions.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

