I am having trouble when trying to convert this function from a Class based one to a Functional based one. In the _spring() i seem to have an issue using the useState() within the context of an Animated component.
CLASS Style
constructor(props) {
super(props);
this.springValue = new Animated.Value(100);
}
state = {
currentIndex: 1,
backClickCount: 0,
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton.bind(this));
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton.bind(this));
}
handleBackButton = () => {
this.state.backClickCount == 1 ? BackHandler.exitApp() : this._spring();
return true;
};
_spring() {
this.setState({ backClickCount: 1 }, () => {
Animated.sequence([
Animated.spring(
this.springValue,
{
toValue: -.07 * height,
friction: 5,
duration: 300,
useNativeDriver: true,
}
),
Animated.timing(
this.springValue,
{
toValue: 100,
duration: 300,
useNativeDriver: true,
}
),
]).start(() => {
this.setState({ backClickCount: 0 });
});
});
}
My attempt at moving it to FUNCTIONAL style is:
const [currentIndex, setCurrentIndex] = useState(1);
const [backClickCount, setBackClickCount] = useState(0);
const springValue = new Animated.Value(100);
const handleBackButton = () => {
backClickCount == 1 ? BackHandler.exitApp() : _spring();
return true;
};
useEffect(() => {
const backHandler = BackHandler.addEventListener(
"hardwareBackPress",
() => {
handleBackButton();
}
);
return () => backHandler.remove();
}, []);
const _spring = () => {**
setBackClickCount(1), () => {
Animated.sequence([
Animated.spring(
springValue,
{
toValue: -.07 * height,
friction: 5,
duration: 300,
useNativeDriver: true,
}
),
Animated.timing(
springValue,
{
toValue: 100,
duration: 300,
useNativeDriver: true,
}
),
]).start(() => {
setBackClickCount(0)
});
});
}
I've lost a comma in making the transition (see the **). How should this function look, as i feel like i'm very close. Would it be better to put it in a useEffect()? If so, how?