UNPKG

react-activity-tracker

Version:

A library to track user interactions and API activity in React apps

46 lines (41 loc) 1.07 kB
export default function patchFetch(onTrack) { const originalFetch = window.fetch; window.fetch = async function (url, options = {}, label = '') { const method = options.method || 'GET'; const body = options.body ? tryParseJSON(options.body) : null; try { const response = await originalFetch(url, options); const cloned = response.clone(); const text = await cloned.text(); const responseBody = tryParseJSON(text); onTrack({ type: 'api', label, url, method, requestBody: body, responseBody, status: response.status, }); return response; } catch (err) { onTrack({ type: 'api', label, url, method, requestBody: body, responseBody: { error: err.message }, status: 'error', }); throw err; } }; } function tryParseJSON(data) { try { return typeof data === 'string' ? JSON.parse(data) : data; } catch { return data; } }