Skip to content
Advertisement

How sum specific array values with input onChange

I’m have a list of objects

{id: 182, symbol: 'ETHUSDT', recommended_to_buy_qty: '42.83213', current_qty_in_portfolio: '8.06928'}
{id: 183, symbol: 'XRPUSDT', recommended_to_buy_qty: '83.47332', current_qty_in_portfolio: '8.79834'}
{id: 184, symbol: 'ADAUSDT', recommended_to_buy_qty: '50.72704', current_qty_in_portfolio: '3.79095'}

I need to sum two values in array with onChange input

On every change values is summed

const [inputValue, setInputValue] = useState(0)

    function handleChange(e) {
        e.preventDefault();
        setInputValue(e.target.value);
}

I’m create input form and it’s works but change all my mapped values at once

<Form.Control onChange={handleChange} value={inputValue} />

How can i change only one item in array at once on every onChange event?

Advertisement

Answer

You can make inputValue store an object. The object can hold each objects id as its key and its associated sum. When mapping over your list, use the id of the current object your iterated on to obtain the value from inputValue. Within your onChange, you can pass the current objects id so that you can update it when you set your object state, eg:

const [inputValue, setInputValue] = useState({});

function handleChange(e, id) {
  e.preventDefault();
  setInputValue(obj => ({...obj, [id]: e.target.value}));
}

Now when you acceess your value, access it via the id of the current object. Below I’m using ?? 0 to use the value of 0 if inputValue[el.id] is undefined due to el.id not being set:

<Form.Control onChange={e => handleChange(e, el.id)} value={inputValue[el.id] ?? 0} />
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement