I have 5 button "35,17,11,8,5" when I press a button I want to add the button's value to a list, so I did that.
import React, { useState } from "react";
import { StyleSheet, Text, View, Pressable, TextInput } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
function AddtoArray(array,value){
console.log('a', 'a');
const [arrayToChange, setArrayToChange] = useState(array);
console.log('a1', 'a1');
const [valueToAdd, setValueToAdd] = useState(value);
console.log('a2', 'a2');
const newArray = () => {
setArrayToChange([...arrayToChange, value]);
};
console.log('b',newArray, 'b');
return newArray;
};
function RouletteExercice1 ({ navigation }){
const [multiplyArray, setMultiplyArray] = useState([]);
return(
<View>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'35'))}}>
<Text>35</Text>
</Pressable>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'17'))}}>
<Text>17</Text>
</Pressable>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'11'))}}>
<Text>11</Text>
</Pressable>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'8'))}}>
<Text>8</Text>
</Pressable>
<Pressable onPress={() => {setMultiplyArray(AddtoArray(multiplyArray,'5'))}}>
<Text>5</Text>
</Pressable>
</View>
)
}
But when I press a button the app say "invalic hook call" and on the console all i have is "a a". Can someone tell me what is the problem ? please
CodePudding user response:
Your AddtoArray function is outside of your functional component, RouletteExercice1.
When you call useState, you're adding state to the functional component that you're calling useState from. You must call useState from the functional component.
That said, you don't need state for arrayToChange or valueToAdd. You're only changing the one array, and you're passing the value to the function.
import React, { useState } from "react";
import { StyleSheet, Text, View, Pressable, TextInput } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
function RouletteExercice1 ({ navigation }){
const [multiplyArray, setMultiplyArray] = useState([]);
function AddtoArray(value){
setMultiplyArray((prev) => [...prev, value])
}
return(
<View>
<Pressable onPress={() => {AddtoArray('35')}}>
<Text>35</Text>
</Pressable>
<Pressable onPress={() => {AddtoArray('17')}}>
<Text>17</Text>
</Pressable>
<Pressable onPress={() => {AddtoArray('11')}}>
<Text>11</Text>
</Pressable>
<Pressable onPress={() => {AddtoArray('8')}}>
<Text>8</Text>
</Pressable>
<Pressable onPress={() => {AddtoArray('5')}}>
<Text>5</Text>
</Pressable>
</View>
)
}