Skip to content

Commit

Permalink
ensure we re evaluate state machine inputs when we play is triggered,…
Browse files Browse the repository at this point in the history
… looks like there maybe additional situations where we are going to need this.
  • Loading branch information
mjtalbot committed Jul 22, 2022
1 parent 1092b44 commit 84b18cc
Showing 1 changed file with 25 additions and 13 deletions.
38 changes: 25 additions & 13 deletions src/hooks/useStateMachineInput.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
import { Rive, StateMachineInput } from '@rive-app/canvas';
import { EventType, Rive, StateMachineInput } from '@rive-app/canvas';

/**
* Custom hook for fetching a stateMachine input from a rive file.
Expand All @@ -18,21 +18,33 @@ export default function useStateMachineInput(
const [input, setInput] = useState<StateMachineInput | null>(null);

useEffect(() => {
if (!rive || !stateMachineName || !inputName) {
setInput(null);
}
function setStateMachineInput() {
if (!rive || !stateMachineName || !inputName) {
setInput(null);
}

if (rive && stateMachineName && inputName) {
const inputs = rive.stateMachineInputs(stateMachineName);
if (inputs) {
const selectedInput = inputs.find((input) => input.name === inputName);
if (initialValue !== undefined && selectedInput) {
selectedInput.value = initialValue;
if (rive && stateMachineName && inputName) {
const inputs = rive.stateMachineInputs(stateMachineName);
if (inputs) {
const selectedInput = inputs.find(
(input) => input.name === inputName
);
if (initialValue !== undefined && selectedInput) {
selectedInput.value = initialValue;
}
setInput(selectedInput || null);
}
setInput(selectedInput || null);
} else {
setInput(null);
}
} else {
setInput(null);
}
setStateMachineInput();
if (rive) {
rive.on(EventType.Play, () => {
// Check if the component/canvas is mounted before setting state to avoid setState
// on an unmounted component in some rare cases
setStateMachineInput();
});
}
}, [rive]);

Expand Down

0 comments on commit 84b18cc

Please sign in to comment.