0

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?

5
  • Can you share your mapping code? Are you mapping over the first list of objects? Commented Dec 17, 2022 at 12:57
  • Your handleChange() doesn't do any summing, where is that logic? Commented Dec 17, 2022 at 13:00
  • summing looks like this for now ` {(Number(inputValue) + Number(recommendationInit.data.recommended_positions[index].current_qty_in_portfolio)).toFixed(5)} ` but it's working Commented Dec 17, 2022 at 13:05
  • 1
    Can you edit your question and add more detail, it is unclear what you are asking and what you are currently doing. What does you function to sum values look like? Which property of your object list are you trying to manipulate? Commented Dec 17, 2022 at 13:10
  • It's looks like this [codesandbox.io/s/clever-booth-kcmecn?file=/src/App.js] but request is from backend and for some reason in codesandbox fake data doesn't want to show up Commented Dec 17, 2022 at 13:19

1 Answer 1

1

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} />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.