Skip to content

Commit

Permalink
Fix for stored state. If the state received is invalid then set the s…
Browse files Browse the repository at this point in the history
…tate to be the default state and return the default state
  • Loading branch information
oliverabrahams committed Jan 15, 2025
1 parent 34042f6 commit 2932aaf
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions libs/@guardian/react-crossword/src/hooks/useStoredState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,17 @@ export function useStoredState<
serializer,
});

const validatedState = useMemo(() => {
const validatedState: T = useMemo(() => {
// If the state is valid, return it (now properly typed).
if (validator(state)) {
return state;
}

// The state is invalid, so return the default value (which may be
// undefined).
// The state is invalid, set the state to the default value and return the default value
// (which may be undefined).
setState(defaultValue);
return defaultValue;
}, [validator, state, defaultValue]);
}, [validator, state, setState, defaultValue]);

return [validatedState, setState, rest] as const;
}

0 comments on commit 2932aaf

Please sign in to comment.