Created
March 7, 2024 06:05
-
-
Save auaicn/210914b73a839ce5a34689b8907e784e to your computer and use it in GitHub Desktop.
Trying to use MappedReactiveVariable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { makeVar, ReactiveVar } from '@apollo/client'; | |
import React, { useEffect, useState, useCallback } from 'react'; | |
import isEqual from 'lodash/isEqual'; | |
type Data = { | |
title: string; | |
date: Date; | |
}; | |
// Create the reactive variable with Map<number, Data> type | |
export const referRequestMetaVar = makeVar<Map<number, Data>>(new Map([ | |
[1, { | |
title: 'InitialValue', | |
date: new Date(), | |
}], | |
// Add more entries as needed | |
])); | |
// Utility method to update a specific key within referRequestMetaVar | |
export const updateReferRequestMetaVarKey = (key: number, newMeta: Data) => { | |
referRequestMetaVar((prevMap) => { | |
const newMap = new Map(prevMap); | |
newMap.set(key, newMeta); | |
return newMap; | |
}); | |
}; | |
// Custom hook to watch changes to a specific key within a reactive variable | |
export const useReactiveVarForKey = <T>(reactiveVar: ReactiveVar<T>, key: number) => { | |
const [value, setValue] = useState(() => reactiveVar()[key]); | |
useEffect(() => { | |
const handleChange = () => { | |
const newValue = reactiveVar()[key]; | |
if (!isEqual(newValue, value)) { | |
setValue(newValue); | |
} | |
}; | |
const unsubscribe = reactiveVar.subscribe(handleChange); | |
return () => { | |
unsubscribe(); | |
}; | |
}, [reactiveVar, key, value]); | |
const setValue = useCallback( | |
(newValue: T) => { | |
setValue(newValue); | |
updateReferRequestMetaVarKey(key, newValue); | |
}, | |
[key] | |
); | |
return { value, setValue }; | |
}; | |
// Example usage | |
// const { value, setValue } = useReactiveVarForKey(referRequestMetaVar, 1); | |
// React component using the custom hook | |
const MyComponent = ({ watchedKey }) => { | |
const { value, setValue } = useReactiveVarForKey(referRequestMetaVar, watchedKey); | |
// Example of using setValue | |
// setValue(newReferRequestMeta); | |
return ( | |
<div> | |
<p>{`${watchedKey}: ${JSON.stringify(value)}`}</p> | |
</div> | |
); | |
}; | |
export default MyComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment