mirror of
https://github.com/Unleash/unleash.git
synced 2025-01-01 00:08:27 +01:00
59a6ef46e8
## Problem The ConstraintAccordionList component was used in multiple places: * Playground * Segment form * StrategyExecution * Change requests * Create strategy * Edit strategy This is problematic because some of the views are just pure visual representations, and other views allow you to interact with and edit the constraints. This causes a situation where the visual representation needs to be aware of the implementation details of editing and mutating constraints. In addition the ConstraintAccordionList is not just a pure rendering of the list, it also keeps internal state on when to show the create button and optional headers. This is makes it hard to make changes when stylings need to be subtly different across components. ## Solution Taking on the full refactor for this is out of scope, but it's unfortunate that the ConstraintAccordionList needs all this internal state. For now I split out the list into it's own component called ConstraintList. I gathered the functions needed for editing and mutating the constraints in a reusable hook and isolated the version of the list used in the new feature strategy edit / create components into it's own component so that the changes in layout will not affect anything else. Ideally we should try to move towards a future where the components don't keep internal state like this but clear boundaries and purposes for the use.
34 lines
868 B
TypeScript
34 lines
868 B
TypeScript
import { useState, useCallback, useRef, useMemo } from 'react';
|
|
|
|
export interface IUseWeakMap<K, V> {
|
|
set: (k: K, v: V) => void;
|
|
get: (k: K) => V | undefined;
|
|
}
|
|
|
|
// A WeakMap associates extra data with an object instance.
|
|
// This hook encapsulates a WeakMap, and will trigger
|
|
// a rerender whenever `set` is called.
|
|
export const useWeakMap = <K extends object, V>(
|
|
initial?: WeakMap<K, V>,
|
|
): IUseWeakMap<K, V> => {
|
|
const ref = useRef(initial ?? new WeakMap<K, V>());
|
|
const [, setState] = useState(0);
|
|
|
|
const set = useCallback((key: K, value: V) => {
|
|
ref.current.set(key, value);
|
|
setState((prev) => prev + 1);
|
|
}, []);
|
|
|
|
const get = useCallback((key: K) => {
|
|
return ref.current.get(key);
|
|
}, []);
|
|
|
|
return useMemo(
|
|
() => ({
|
|
set,
|
|
get,
|
|
}),
|
|
[set, get],
|
|
);
|
|
};
|