From 3b4c66bc98a1ff83722ce15bfa81a6174f48bf9d Mon Sep 17 00:00:00 2001 From: Jay Meistrich Date: Thu, 12 Oct 2023 21:42:24 +0200 Subject: [PATCH] rename to enableReactTracking, add params for auto mode or warning if unobserved --- ...tAutoTracking.ts => enableReactTracking.ts} | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) rename src/config/{enableReactAutoTracking.ts => enableReactTracking.ts} (69%) diff --git a/src/config/enableReactAutoTracking.ts b/src/config/enableReactTracking.ts similarity index 69% rename from src/config/enableReactAutoTracking.ts rename to src/config/enableReactTracking.ts index 421fba878..552782a7c 100644 --- a/src/config/enableReactAutoTracking.ts +++ b/src/config/enableReactTracking.ts @@ -32,17 +32,27 @@ function needsSelector() { return false; } -export function enableReactAutoTracking() { +interface ReactTrackingOptions { + auto?: boolean; // Make all get() calls act as useSelector() hooks + warnUnobserved?: boolean; // Warn if get() is used outside of an observer +} + +export function enableReactTracking({ auto, warnUnobserved }: ReactTrackingOptions) { const { get } = internal; configureLegendState({ observableFunctions: { get: (node: NodeValue, options?: TrackingType | (GetOptions & UseSelectorOptions)) => { if (needsSelector()) { - return useSelector(() => get(node, options), isObject(options) ? options : undefined); - } else { - return get(node, options); + if (auto) { + return useSelector(() => get(node, options), isObject(options) ? options : undefined); + } else if (process.env.NODE_ENV === 'development' && warnUnobserved) { + console.warn( + '[legend-state] Detected a `get()` call in an unobserved component. You may want to wrap it in observer: https://legendapp.com/open-source/state/react-api/#observer-hoc', + ); + } } + return get(node, options); }, }, });