Value Becomes Undefined Because Of Setstate
Solution 1:
You are defining classifier
as a let
variable. It is not a state so it does not persist across re-renders. Every time your component gets re-rendered the code let classifier: any;
gets executed and classifier
becomes undefined
.
When you call a setState
function such as setTrainingComplete(true)
this changes the state of your component and causes it to re-render. Therefore you lose the value of classifier
.
You want to keep the value of classifier
so you need to store it using a useState
or useRef
hook. I generally use useRef
when dealing with complex objects from external libraries which have their own internal state. So that's what I suggest here.
const classifierRef = useRef<any>();
functiontrain() {
const classifier = classifierRef.current;
console.log('classifier in train', classifier);
classifier?.train((lossValue: any) => {
console.log('Loss is', lossValue);
if (lossValue == null) {
setTrainingComplete(true);
}
});
console.log('classifier in train', classifier);
}
Solution 2:
You have to add the useRef for the capture variable as well. https://dementorwriter.medium.com/picture-classification-with-react-ml5-c45672aeb961
Post a Comment for "Value Becomes Undefined Because Of Setstate"