I'm using ml5.js to train an ML model. I have to add images to the model using the webcam. The train function works fine with the current code. However, when I try to set a state within my if else statement inside the train function, it throws an error when I try to test it using the test button.
the value of classifier
becomes undefined
.
export const Component: React.FC<ComponentProps> = (props: ComponentProps) => {
let classifier: any;
classifier = featureExtractor.classification(capture, videoReady);
}
function final() {
classifier.classify(capture, (error, result) => {
setPrediction(label);
});
}
return (<div>
<Button variant="contained" color="primary" onClick={() => final()}>testing!</Button>
</div>
</div>)
;
};
classifier
is a variable so it would re-render each time. useRef could be used here but I couldn't figure out how.
const classifier = useRef()
classifier.current
accessing it like this still gave me the error. I also tried making a state for the classifier itself but that did not seem to work for me either.
Here's a Codesandbox to try the full thing. To see the error, you can set a state in the if else statement of the train function:
https://codesandbox.io/s/hardcore-solomon-zb34l?file=/src/Component.tsx