-2

When a list item is clicked, the modifyItem() is called to append a new string to the items array.

From the console logs, it seems that the items array had been modified before the push method (*** below) is even called?? The statements in the function are not executed in sequence?

Appreciate some light shed on this.

Thank you!

Console Log Output:

Items BEFORE modification ["1. Click me and check console log", "2. Placeholder", "additonal text"] // ***

Items AFTER modification ["1. Click me and check console log", "2. Placeholder", "additonal text"]

App.jsx

import List from './List'
import "../styles.css";

export default function App()
{
  const items = ['1. Click me and check console log', '2. Placeholder']

  function modifyItem()
  {
    console.log('Items BEFORE modification')
    console.log(items)
    items.push('additonal text')
    console.log('Items AFTER modification')
    console.log(items)
  }
  return (
    <div className="App">
      <ul>
        { items.map((item, index) =>
        {
          return <List key={index} id={index} modifyItem={modifyItem} text={item} />
        })}
      </ul>
    </div>
  );
}

List.jsx

function List(props)
{
  function modifyMe()
  {
    console.log('Start of ModifyMe')
    props.modifyItem(props.index)
    console.log('End of ModifyMe')
  }
  return <li onClick={ modifyMe } >{ props.text }</li>
}

Codesandbox link here

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
Akhran
  • 13
  • 4
  • 1
    Does this answer your question? [console.log() shows the changed value of a variable before the value actually changes](https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch) – Dennis Vash May 16 '20 at 09:40
  • Check the behavior with debugger + breakpoint instead. – Dennis Vash May 16 '20 at 09:41

1 Answers1

0

Please make a copy of the ite

let items = ['1. Click me and check console log', '2. Placeholder'];
    
  console.log('Items BEFORE modification');
  console.log(items);
  items = [...items];
  items.push('3. Additonal text');
  console.log('Items AFTER modification');
  console.log(items);

ms before modifying. Here is an example to handle this job.

Sourav Singh
  • 878
  • 1
  • 8
  • 14
  • I modified the code to make a copy of the items array, however the copied array still contain the additional string before the push() method was called. – Akhran May 16 '20 at 10:34
  • Please check this sandbox code https://codesandbox.io/s/exciting-cartwright-swd82?file=/src/components/App.js – Sourav Singh May 16 '20 at 10:48