Reputation: 263
Today i have tried to create function that updates every next index of array. I used this code :
import React, { useState } from "react";
import { StyleSheet, Text, View, Button } from "react-native";
import update from "immutability-helper";
export default function App() {
const initialArray = [1, 2, 3];
const [arr, setArr] = useState([]);
var num = 0;
function test() {
num = num + 1;
setArr(update(initialArray, { [num]: { $apply: () => 444 } }));
}
return (
<View style={styles.container}>
<Text>{arr}</Text>
<Button title="change next index" onPress={() => test()} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
Unfortunately, num = num + 1; not working when call this function again and again? Where is problem? I used this lib
Upvotes: 1
Views: 279
Reputation: 6869
num is local variable in function so when your component re-renders it gets initialised with 0 again.
you can use useRef hook to store mutable value between re-renders.
export default function App() {
const initialArray = [1, 2, 3];
const [arr, setArr] = useState([]);
const numRef = useRef(0);
function test() {
numRef.current = numRef.current + 1;
setArr(update(initialArray, { [numRef.current]: { $apply: () => 444 } }));
}
return (
<View style={styles.container}>
<Text>{arr}</Text>
<Button title="change next index" onPress={() => test()} />
</View>
);
}
Upvotes: 3