From 07aca7ce0df0b3a5a7461d94ad73b7bc8a64a848 Mon Sep 17 00:00:00 2001 From: Bluebberies Date: Sun, 27 Oct 2024 11:13:59 +0100 Subject: [PATCH] Handled invalid formatter function props being passed --- src/index.js | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index ac312b7..d6d00d3 100644 --- a/src/index.js +++ b/src/index.js @@ -153,11 +153,38 @@ export default function TimeAgo({ ? { ...passDownProps, dateTime: dateParser(date).toISOString() } : passDownProps - const nextFormatter = defaultFormatter.bind(null, value, unit, suffix) + const nextFormatter = (value, unit, suffix) => { + // Use the default formatter if `formatter` is not a valid function or if it doesn't behave correctly + if (typeof formatter !== 'function') { + console.warn( + '[react-timeago] Formatter is not a function. Using default formatter.', + ) + return defaultFormatter(value, unit, suffix, then, nextFormatter, now) + } + try { + // Call the formatter to see if it behaves correctly + const result = formatter(value, unit, suffix, then, nextFormatter, now) + // If the result is falsy, fall back to defaultFormatter + if (!result) { + console.warn( + '[react-timeago] Formatter is invalid. Using default formatter.', + ) + return defaultFormatter(value, unit, suffix, then, nextFormatter, now) + } + return result + } catch (error) { + console.warn( + '[react-timeago] Formatter is invalid. Using default formatter.', + error, + ) + return defaultFormatter(value, unit, suffix, then, nextFormatter, now) + } + } + return ( - {formatter(value, unit, suffix, then, nextFormatter, now)} + {nextFormatter(value, unit, suffix)} ) }