-2

I am playing around with some react code, and observed unexpected (to me) behaviour. Can someone please explain whats going on?

export default function AnswerBox(props: any) {
    const before = props.answers;
    console.log('const before ', before);
    props.answers.map((value: any) => {value.selected = 'asdfasdfasdf'})
    console.log('answer props after' , props.answers);

Both of the log lines show an array of objects with 'selected':'asdfasdfasdf'

Is there some tricky async business I'm missing here? Thanks in advance.

Allen H.
  • 318
  • 6
  • 19
  • 2
    1. Don't mutate props. 2. Don't use .map for side effects. 3. Console logs are not guaranteed to happen synchronously, and you are logging a reference to a mutable object. – Jared Smith Jun 04 '20 at 23:35
  • 1
    @JaredSmith thanks for the comments, it is appreciated. What is considered a "side effect" of map (and other array methods) ? – Allen H. Jun 05 '20 at 00:31
  • Side effects are things that happen in functions that don't depend only on the inputs. The callback you pass to map doesn't simply return a value, it mutates an external object. Arrays have a `.forEach` method for side effective functions, map is intended to transform the array based on the return values. Your problem though is that when you log an object in the console in certain implementations (like chrome) it logs a live view of the object, not a snapshot of its state at the time you called `console.log`. – Jared Smith Jun 05 '20 at 02:31

1 Answers1

0

For objects and arrays containing other objects or arrays, copying these objects requires a deep copy. Otherwise, changes made to the nested references will change the data nested in the original object or array , here the code :

const before=JSON.parse(JSON.stringify(props.answers));

If you have complex object, with Dates, functions, undefined, Infinity, [NaN], RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays.

I would suggest usin.

Pluto
  • 853
  • 1
  • 8
  • 28
Nonik
  • 645
  • 4
  • 11