I use delete button to splice the array successfully, but it the list delete the last object that I don't want it be deleted. I use console.log() to see if the object I designated to delete is deleted, the result is Yes, but the list on the screen shows that it delete the last thing of the array. Here's the code of array:
const [totalDaysData, setTotalDaysData] = useState([]);
const {Name, days} = route.params || {};
const [totalDaysData, setTotalDaysData] = useState([]);
useEffect(()=>{
if (totalDaysData.length === 0) {
for (let i = 1; i <= days; i ) {
totalDaysData.push({days:i,activity:[]});
setTotalDaysData([...totalDaysData]);
};
} else {
return;
};
Here's my code:
{totalDaysData.map((item,index) =>(
<View
key={index}
>
<TouchableOpacity>
<View style={{flexDirection: 'row',width:width}}>
<View style={{width:width * 0.8}}>
<Text style={{marginRight:height * 0.2}}>{item.days}</Text>
</View>
<TouchableOpacity
onPress={()=>{
item.activity.push({time:'',duration:'',activityName:'',description:''});
setTotalDaysData([...totalDaysData]);
}}
style={{width:width * 0.2}}>
<AntDesign name="pluscircle" size={height * 0.05} color="black" />
</TouchableOpacity>
</View>
</TouchableOpacity>
{item.activity.map((event, index)=>(
<View
key={index}
>
<TextInput
placeholder={'Time'}
onChangeText={(text)=>{
event.time = text;
}}
/>
<TouchableOpacity
onPress={()=>{
item.activity.splice(index, 1);
setTotalDaysData([...totalDaysData]);
}}
>
<Text>delete</Text>
</TouchableOpacity>
</View>
How to solve this ?
CodePudding user response:
you cant splice array inside the array and use map inside other array
CodePudding user response:
Instead of mutating the object, build a new state object and set it.
<TouchableOpacity
onPress={() => {
// Create a new list with one item removed
setTotalDaysData([...totalDaysData.filter((_, i) => i !== index)]);
}}
>
// or
<TouchableOpacity
onPress={() => {
// Create a new list with one element removed
// from a list on an object in a list
setTotalDaysData([...totalDaysData.map(itm => {
if (itm.id === item.id) return {...item, activity: item.activity.filter((_, i) => i !== index)};
return itm;
})]);
}}
>
