I have 3 inputs and plus button when pressed it I want to add another 3 inputs so with his state,
the state like this
state={
toolsUsed: [
{
id: (Math.random() * 150).toString(),
name: '',
price: '',
count: '',
},
{..},
],
}
in the first 3 input component, I want when I add a change value text set the state with this value!
but I tried it but after changing the text I got in a state
toolsUsed => [" ","text"]
what I want to achieve
toolsUsed => [{name:'text",count:'..',price:'....',id:'..'},{...}]
UI
here's my code
renderToolsUsed = () => {
const {toolsUsed} = this.state;
const prom = toolsUsed.map(({name, id, price, count}, i) => {
return (
<View>
<View style={styles.toolsItem}>
<TextInput
onChangeText={name =>
this.setState(
prevState => {
return {
...prevState,
toolsUsed: [prevState.toolsUsed[i].name, name],
};
},
() => console.log(this.state.toolsUsed),
)
}
value={name}
key={id}
/>
</View>
<View style={styles.toolsItem}>
<TextInput
onChangeText={count => this.setState({})}
value={count}
key={id}
/>
</View>
<View style={styles.toolsItem}>
<TextInput
onChangeText={price => this.setState({})}
value={price}
key={id}
/>
</View>
<TouchableOpacity onPress={() =>
this.setState(prevState => {
return {
...prevState,
toolsUsed: prevState.toolsUsed.length + 1,
};
})
}> **// heres i got error "toolsUsed.map not a function**
<Text>+</Text>
</TouchableOpacity>
</View>
);
});
return prom;
}
JSX
...
render(){
return(
<View style={styles.toolsContainer}>
<Text>
Tools
</Text>
{this.renderToolsUsed()}
</View>
);
}
EDIT~1
maybe :D solve plus function
onPress={() => {
let newInput = this.state.toolsUsed.length;
this.setState(prevState => ({
toolsUsed: prevState.toolsUsed.concat([newInput]),
}));
}
EDIT ~ 2
I add a minus button to delete the last object in tools array,
here two ways to handle it, but I have something weird on the first way it's work well I don't know why! but when I comment first var newInput it's don't delete the last item
onPress={() => {
// first way
let newInput = this.state.toolsUsed.pop();
this.setState(prevState => ({
toolsUsed: prevState.toolsUsed.filter(
tool => tool.id !== id,
),
}));
// Second
let rowDeleted = [...this.state.toolsUsed];
rowDeleted.splice(-1, 1);
this.setState({toolsUsed: rowDeleted});
}}

id, then you're burying a bug, since it won't happen often, but it will happen, that is, generating the sameid.id