I am trying to use useEffect and useRef() to get the latest value of my counter as well as compare to the previous value so that I know if I need to call the addValues or removeValues function.
I followed the directions here I'm working with Typescript and when I set prevSubjectAddressCounterRef.current = subjectAddressCounter;
I get the error TS2322: Type 'number' is not assignable to type 'undefined'.
How can I fix this error and ensure that when I update the count on the state that I am working with the latest value?
Please see the relevant code below.
const FormGroup = prop => {
const [subjectAddressCounter, setSubjectAddressCounter] = useState(0); // changing to 0 || undefined causes this not to function correctly because you can't add to undefined
const prevSubjectAddressCounterRef = useRef();
useEffect(() => {
prevSubjectAddressCounterRef.current = subjectAddressCounter; // this causes Typescript error above
if (prevSubjectAddressCounterRef.current < subjectAddressCounter) {
// call function to addValues
addValues();
}
if (prevSubjectAddressCounterRef.current === subjectAddressCounter) {
// call function to removeValues
removeValues();
}
}, [subjectAddressCounter]);
const addSection = section => {
if (section.section === SectionTitle.subjectAddress) {
setSubjectAddressCounter(prevCount => prevCount + 1);
}
};
const removeSection = section => {
if (section.section === SectionTitle.subjectAddress) {
setSubjectAddressCounter(prevCount => prevCount - 1);
}
};
return (
...
button onClick={() => addSection(form)}
button onClick={() => removeSection(form)}
)
}
I believe you need to pass the initial value and define the type of the const because undefined
is not equal to number
, that's why is throwing the error Type 'number' is not assignable to type 'undefined'
. I think it should look like this:
const prevSubjectAddressCounterRef = useRef<number>(0);