Add a new element to array or update the existing one (React state)

Antoni Kepinski :

I'm building an expression parser, which has a 2 column interface with textboxes. You enter the expression on the left (ex. 1+2) and you see the result on the right. Expression in each line is added to an array of strings, like so:

12+3
1-2        --->   ['12+3', '1-2', 44+2']
44+2

Now, I want to parse each expression with a function and pass it to another array (React state), which contains results:

['12+3', '1-2', 44+2'] --> [15, -1, 46]

This is the code (it runs every time the left textbox value changes):

const [results, setResults] = useState([]);

expressions?.map(async exp => {
    // Custom function that evaluates the expression
    const parsed = await parse(exp);
    const concat = [...results, parsed];

    setResults(concat.filter((item, pos) => concat.indexOf(item) === pos));
});

I would like the results to be up-to-date with expressions, so that when one of them changes the result of this expression is updated:

Expressions:
[
    '10+5',
    '5+5',  <-- User changes 5 to 3
    '3+3'
]

Results:
[
    15,
    10,  <-- Instantly changes to 8 (no new element is added)
    6
]

Unfortunately, currently, a new element is added to the results array once I change the previous expression.

ssk :

New elements are added because you keep adding it to state by concat = [...results, parsed]; Try this.

const [results, setResults] = useState([]);
let concat = []
expressions?.map(async exp => {
    // Custom function that evaluates the expression
    const parsed = await parse(exp);
    concat = [...concat, parsed];    
});
setResults(concat);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29847&siteId=1