Data binding not working with useRive hooks in rive-react-native v9.3.1
Description
I'm experiencing problems with data binding in rive-react-native v9.3.1. The useRiveNumber hook isn't successfully updating values in my Rive animation.
Environment
- rive-react-native version: 9.3.1
- React Native version: 0.76.9
- Platform: [Both]
Reproduction Steps
- Set up a basic Rive component with the rewards.riv file
- Attempt to use useRiveNumber to update the 'Energy_Bar/Lives' value
- Press button to trigger the update
- Observe that the animation doesn't reflect the change
Expected Behavior
The Lives counter in the animation should update to the new value (10) when the button is pressed.
Actual Behavior
- The Lives counter doesn't update
- console.log shows {lives: null, setLives: [Function]}
- No errors are displayed
Code Example
import React from 'react'
import { View, useWindowDimensions, Button } from 'react-native'
import Rive, {
Fit,
useRive,
AutoBind,
RNRiveErrorType,
RNRiveError,
useRiveNumber,
} from 'rive-react-native'
export const RiveTestView = () => {
const { width } = useWindowDimensions()
const [setRiveRef, riveRef] = useRive()
let [lives, setLives] = useRiveNumber(riveRef, 'Energy_Bar/Lives')
const onChangeLives = () => {
if(!setLives) {
return
}
setLives(10)
}
console.log({lives, setLives})
return (
<View >
<View style={{ width, height: '100%' }}>
<Button title="Update Rive Text" onPress={onChangeLives} />
<Rive
ref={setRiveRef}
fit={Fit.Layout}
layoutScaleFactor={1}
autoplay={true}
dataBinding={AutoBind(true)}
stateMachineName={'State Machine 1'}
source={require('./assets/rewards.riv')}
onError={(riveError: RNRiveError) => {
switch (riveError.type) {
case RNRiveErrorType.DataBindingError: {
console.error(`${riveError.message}`)
return
}
default:
console.error('Unhandled error')
return
}
}}
/>
</View>
</View>
)
}
+1, experiencing the same issue 👍🏻
I’ve tried using both useRiveNumber and setNumber, but the issue persists.
I also attempted delaying the data binding on mount, but it didn’t work consistently.
It seems the problem lies in the data binding itself—no matter the specific method used. After a hot reload, the binding appears to work correctly.
I can’t share the full code publicly, so I’ve opened a private Rive support ticket (ref: RIV-10056) with a minimal reproduction of the issue—just in case any Rive admin sees this !
(as of now, the ticket is in progress, i'll let you know if I have any update)
+1 We are experiencing similar issues, incredibly inconsistent to work with.
Quick update, we've noticed through testing that when trying to change data, it won't update the canvas until it has been physically interacted with.
For example:
The "Change Pos X" button is pressed in our app. Rive Canvas does not update to the new values You then press (or interact) with the Rive Canvas in any way, and it then updates to the correct value (moves to the correct position)
I will also note that this test Rive file has no listeners or state changes internally, so there are no internal conflicts; it is just an example test file.
Any updates on this?
We ended up solving our issue, which wasn't exactly correlated to this one. We found that databinding seemed not to take effect when the render had paused, and new values inputted via data binding did not seem to "re-activate" the paused rive render.
I don't know if this is an architecture issue or an unfortunate oversight on Rives end, considering I remember reading that they implemented this for "memory and performance" saving.
However, our fix came through the need to use an animation "exciter" (which ended up being a permanently rotating 1px box) to ensure that the Rive render was active at all times.
All that being said, databinding is still inconsistent on some occasions, especially when initially loading, so we are still waiting and watching this thread.
Thanks for letting us know! This seems to be a combination of two separate issues:
- Initializing the view model instance is flaky
- We don't automatically restart the render loop when updating the view model in a settled state
For issue 1
The issue stems from using the source prop in development mode, or using a network .riv file, then the .riv may not be loaded/parsed before the useRive file hook gets its reference to the underlying view. This is a bug, and we'll get this fixed ASAP. However, this should only be an iOS issue - if anyone is experiencing similar issues on Android, please let me know and provide a reproducible sample.
You can step around this for now by observing the onStateChanged callback and only then setting the AutoBind to true, and then you can safely interact with the view model. This is hack! We'll get the useRive hook fixed soon. See this sample to step around it for now:
import { useEffect, useRef, useState } from 'react';
import { SafeAreaView, StyleSheet } from 'react-native';
import Rive, {
Alignment,
AutoBind,
Fit,
useRive,
useRiveString,
} from 'rive-react-native';
export default function Simple() {
const [setRiveRef, riveRef] = useRive();
let [buttonText, setButtonText] = useRiveString(riveRef, 'String property');
console.log('Button Text:', buttonText);
const initialValuesSet = useRef(false);
const [showRive, setShowRive] = useState(false);
const [autoBind, setAutoBind] = useState(false); // Track AutoBind state
const autoBindSet = useRef(false); // Track if AutoBind has been set
useEffect(() => {
const timer = setTimeout(() => {
setShowRive(true);
}, 2000);
return () => clearTimeout(timer);
}, []);
useEffect(() => {
if (initialValuesSet && buttonText) {
// Set initial values for the Rive string property
setButtonText('Hello, Rive!');
initialValuesSet.current = true;
riveRef?.play();
}
}, [riveRef, buttonText, setButtonText]);
return (
<SafeAreaView style={styles.safeAreaViewContainer}>
{showRive && (
<Rive
fit={Fit.Contain}
alignment={Alignment.Center}
style={styles.animation}
dataBinding={AutoBind(autoBind)}
autoplay={true}
stateMachineName="DuneTalk"
ref={setRiveRef}
onStateChanged={(_, __) => {
if (!autoBindSet.current) {
setAutoBind(true);
autoBindSet.current = true;
}
}}
source={require('../../assets/rive/dunita-talking.riv')}
/>
)}
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeAreaViewContainer: {
flex: 1,
},
container: {
flexGrow: 1,
alignItems: 'center',
justifyContent: 'center',
},
animation: {
width: '100%',
height: 300,
},
});
For issue 2
None of the runtimes are currently restarting the render loop when the graphic is settled upon updating a view model. We're discussing the best way to do this internally. For now, you can simply call play again if you believe your state machine to be settled and you need to update your view model data.
If there are any other issues please provide a reproducible sample and I can take a look.
Please try version 9.3.3 for issue 1
Hi @HayesGordon ! Thanks for your help on this one.
For your info : I've been using the hack for 5 days, and it works consistently. Yet version 9.3.3 does not seem to solve the binding issue. As soon as I remove the hack solution, data binding do not work anymore.
Hi @HayesGordon ! Thanks for your help on this one.
For your info : I've been using the hack for 5 days, and it works consistently. Yet version 9.3.3 does not seem to solve the binding issue. As soon as I remove the hack solution, data binding do not work anymore.
@0xEzis on iOS, Android, or both?
If you can provide a minimal reproducible sample that will be great. This will most likely involve having native Rive iOS and Android expose onLoad callback which they currently don't.
@0xEzis Here's an example I got to work
const petToResourceName = () => "charity_3";
function parseColor(color: string): RiveRGBA {
const hex = color.replace(/^#/, "");
const isValidHex = /^[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$/.test(hex);
if (!isValidHex) {
console.warn(`Rive invalid hex color: ${color}`);
return { r: 0, g: 0, b: 0, a: 255 };
}
let r = parseInt(hex.slice(0, 2), 16),
g = parseInt(hex.slice(2, 4), 16),
b = parseInt(hex.slice(4, 6), 16),
a = 255;
// Optionally parse alpha channel if present
if (hex.length === 8) {
a = parseInt(hex.slice(6, 8), 16);
}
return { r, g, b, a };
}
export const RivePetSprite: React.FC<React.PropsWithChildren<PetSpriteProps>> =
memo(
({
pet: {
speciesId = SpeciesId.Anxious,
stage: _stage = 1,
variant,
isVivid,
headItemId,
neckItemId,
outline,
},
size,
bounce: _bounce,
shadow,
style,
bubble,
glowShadow,
}) => {
const riveRef = useRef<RiveRef>(null);
const [autoBind, setAutoBind] = useState(isAndroid);
const hasAutoBind = useRef(isAndroid);
useEffect(() => {
if (!autoBind) {
return;
}
if (isVivid && typeof variant === "number") {
const { eye, primary, secondary } =
vividColorMap[variant as keyof typeof vividColorMap];
riveRef.current?.setColor("Primary", parseColor(primary));
riveRef.current?.setColor("Secondary", parseColor(secondary));
riveRef.current?.setColor("Eye", parseColor(eye));
} else {
riveRef.current?.setColor("Primary", parseColor("#000000"));
riveRef.current?.setColor("Secondary", parseColor("#3E3E60"));
riveRef.current?.setColor("Eye", parseColor("#FFFFFF"));
}
if (headItemId) {
riveRef.current?.fireState("sm", "headItem");
}
if (neckItemId) {
riveRef.current?.fireState("sm", "neckItem");
}
}, [headItemId, neckItemId, isVivid, variant, autoBind]);
return (
<View
style={[
{
width: size,
height: size,
justifyContent: "center",
alignItems: "center",
},
style,
]}
pointerEvents="none"
>
<Rive
ref={riveRef}
resourceName={petToResourceName()}
dataBinding={AutoBind(autoBind)}
style={{
width: size,
height: size,
}}
onStateChanged={() => {
if (!hasAutoBind.current) {
setAutoBind(true);
hasAutoBind.current = true;
}
}}
referencedAssets={{
...(neckItemId
? {
neckItem: {
source: isAndroid
? { resource: itemImgMap[neckItemId] }
: itemImgMap[neckItemId],
},
}
: undefined),
...(headItemId
? {
headItem: {
source: isAndroid
? { resource: itemImgMap[headItemId] }
: itemImgMap[headItemId],
},
}
: undefined),
}}
autoplay={bounce}
/>
</View>
);
}
);
@HayesGordon is there any update on this? We are blocked to use rive due to this issue.
I've chatted with the team about exposing an onLoad for native iOS and Android. It's on the list, but they are wrapping up other work first. Same for restarting the render loop automatically.
I've mentioned this in a few other threads, but we are working on a new React Native runtime that will change the ownership of Rive files (.riv) instances and View Model Instances to be on the React Native side. You'll have much more control then.
@ishaan1995 does the above workaround using the onStateChanged not work for you? If it's not working, you may be incorrectly using data binding. We won't be able to investigate without you providing a minimal reproducible sample.
Any update on this one? I'm interested in a fix too as I'm now using the hackish workaround (a permanently rotating 1px box, thanks @smiry039).
@0xEzis Here's an example I got to work
const petToResourceName = () => "charity_3";
function parseColor(color: string): RiveRGBA { const hex = color.replace(/^#/, "");
const isValidHex = /^[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$/.test(hex); if (!isValidHex) { console.warn(
Rive invalid hex color: ${color}); return { r: 0, g: 0, b: 0, a: 255 }; }let r = parseInt(hex.slice(0, 2), 16), g = parseInt(hex.slice(2, 4), 16), b = parseInt(hex.slice(4, 6), 16), a = 255;
// Optionally parse alpha channel if present if (hex.length === 8) { a = parseInt(hex.slice(6, 8), 16); }
return { r, g, b, a }; }
export const RivePetSprite: React.FC<React.PropsWithChildren
> = memo( ({ pet: { speciesId = SpeciesId.Anxious, stage: _stage = 1, variant, isVivid, headItemId, neckItemId, outline, }, size, bounce: _bounce, shadow, style, bubble, glowShadow, }) => { const riveRef = useRef (null); const [autoBind, setAutoBind] = useState(isAndroid); const hasAutoBind = useRef(isAndroid); useEffect(() => { if (!autoBind) { return; } if (isVivid && typeof variant === "number") { const { eye, primary, secondary } = vividColorMap[variant as keyof typeof vividColorMap]; riveRef.current?.setColor("Primary", parseColor(primary)); riveRef.current?.setColor("Secondary", parseColor(secondary)); riveRef.current?.setColor("Eye", parseColor(eye)); } else { riveRef.current?.setColor("Primary", parseColor("#000000")); riveRef.current?.setColor("Secondary", parseColor("#3E3E60")); riveRef.current?.setColor("Eye", parseColor("#FFFFFF")); } if (headItemId) { riveRef.current?.fireState("sm", "headItem"); } if (neckItemId) { riveRef.current?.fireState("sm", "neckItem"); } }, [headItemId, neckItemId, isVivid, variant, autoBind]); return ( <View style={[ { width: size, height: size, justifyContent: "center", alignItems: "center", }, style, ]} pointerEvents="none" > <Rive ref={riveRef} resourceName={petToResourceName()} dataBinding={AutoBind(autoBind)} style={{ width: size, height: size, }} onStateChanged={() => { if (!hasAutoBind.current) { setAutoBind(true); hasAutoBind.current = true; } }} referencedAssets={{ ...(neckItemId ? { neckItem: { source: isAndroid ? { resource: itemImgMap[neckItemId] } : itemImgMap[neckItemId], }, } : undefined), ...(headItemId ? { headItem: { source: isAndroid ? { resource: itemImgMap[headItemId] } : itemImgMap[headItemId], }, } : undefined), }} autoplay={bounce} /> </View> ); }); Does this actually work or you made a custom rive package for it???