I have this ref that holds an array. I have a context that holds the ref and another context with information about the ref. I wanted to make the items of the array reactive, so I wrapped the data in an observable class and build this hook to hide the subscribe/unsubscribe logic:
const useData = (index: number) => {
const refs = useRefData(); // A hook that gets the ref from a context and returns it
const { dataLength} = useContext(StatContext);
const observable = refs.current?.[index];
const [value, setValue] = useState<Readonly<DataModel>>(
observable?.Data ?? PLACEHOLDER,
);
useEffect(() => {
const observable = refs.current?.[index];
const subscriber: ObservableSubscriber<DataModel> = (
newValue,
oldValue,
isPartial,
) => {
const updatedValue = isPartial
? ({ ...oldValue, ...newValue } as DataModel)
: (newValue as InsightApiResponse);
setValue(updatedValue);
};
observable?.subscribe(subscriber);
return () => {
observable?.unsubscribe(subscriber);
};
}, [dataLength]);
return value;
};
My problem is that if one of the items in the array gets deleted, the dataLength property gets updated, the hook rerenders, it fetches the new correct value, but in the UI it always appears that the last item was the one deleted. That makes some sense since I am rendering the items iterating from 0 to dataLength to provide the items with indexes to call the hook. What doesn't make sense is even though the hook data gets updated so each UI item displays it's new correct data item after an element gets deleted, the UI elements don't rerender. Is there something wrong with my hook?