Problem when trying to change input value
Solution 1:
You store the dataFromBackend
in variable thats the issue.! You need to store dataFromBackend
in state and on input (handleInputChange)
change you need to update this array !
On Add
btn click you need to push new object in dataFromBackend
array
Show this code it's help you !
const BasicInformation = () => {
const { Panel } = Collapse;
const [dataFromBackend, setDataFromBackend] = useState([
{ id: 2, depositeAmt: '500' },
{ id: 3, depositeAmt: '1500' },
]);
const [totalCount, setTotalCount] = useState(
dataFromBackend
.map((item) => item.depositeAmt)
.reduce((prev, curr) => +prev + +curr, 0)
);
const onSubmit = (data) => {
console.log(data);
};
const handleInputChange = (index, value) => {
let arr = [...dataFromBackend];
arr[index].depositeAmt = value;
setDataFromBackend(arr);
};
useEffect(() => {
let count = dataFromBackend
.map((item) => item.depositeAmt)
.reduce((prev, curr) => +prev + +curr, 0);
setTotalCount(count);
}, [dataFromBackend]);
const addNewField = () => {
let id = new Date().getTime();
setDataFromBackend(oldArray => [...oldArray, { id: id, depositeAmt: 0 }]);
};
return (
<Form onFinish={(e) => onSubmit(e)}>
<Form.List name="users" initialValue={dataFromBackend}>
{(fields, { add }) => {
return (
<>
total Deposit Amount: $ {totalCount}
<Button
type="dashed"
onClick={() => {
add();
addNewField();
}}
block
>
Add
</Button>
{fields.map((field, i) => (
<Collapse
key={i}
accordion
style={{
background: 'rgba(25, 103, 210, 0.08)',
border: 'none',
}}
>
<Panel style={{ border: 'none' }} header="Amount :">
<Form.Item
name={[field.name, 'depositeAmt']}
label="Amount"
fieldKey={[field.fieldKey, 'depositeAmt']}
>
<Input
type="number"
onChange={(e) => handleInputChange(i, e.target.value)}
/>
</Form.Item>
</Panel>
</Collapse>
))}
</>
);
}}
</Form.List>
<Button type="primary" htmlType="submit">
send
</Button>
</Form>
);
};
ReactDOM.render(<BasicInformation />, document.getElementById('container'));