How to implement a webcam component gracefully and correctly?

I am trying to write a webcam component (https://playground.solidjs.com/anonymous/ea52969d-05f3-4da7-b171-1c4a76419fad ). But I am not sure how to stop the webcam stream that is loading when the component is unmounted. The code I implemented is something like this:
const owner = getOwner();
onCleanup(() => {
runWithOwner(owner, () => {
createEffect(
on(
() => state,
() => {
// perform cleanup
},
),
);
});
});
const owner = getOwner();
onCleanup(() => {
runWithOwner(owner, () => {
createEffect(
on(
() => state,
() => {
// perform cleanup
},
),
);
});
});
It seems to work correctly, but I am not very familiar with the mechanism of solid. Is there a better way to handle this situation? I would appreciate any suggestions or feedback.
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template
2 Replies
REEEEE
REEEEE8mo ago
you shouldn't need the createEffect inside the onCleanup onCleanup will get called when the component unmounts This should be all you need
onCleanup(() => {
if (isWebcamOpened()) {
webcamStream()!
.getVideoTracks()
.forEach((track) => track.stop());
}
});
onCleanup(() => {
if (isWebcamOpened()) {
webcamStream()!
.getVideoTracks()
.forEach((track) => track.stop());
}
});
HimeHina
HimeHina8mo ago
If the state of the webcam is pending when onCleanup is executed, checking isWebcamOpened only will not stop the track. I might have found a better way to handle this, using createReaction. Here is the updated code: https://playground.solidjs.com/anonymous/ced4edfd-7038-47a1-b311-5c45248d00f4 What do you think?
Solid Playground
Quickly discover what the solid compiler will generate from your JSX template