ln09nv2
ln09nv2

Reputation: 1343

Input value is rendered twice as one element when pushed into an array

When I type a word into the input and press the Append button, the word is then pushed into an array.

However, the word is rendering twice as one element in the array. "Foo" would be pushed into the array as ["Foo Foo"]

When Undo button is pressed, the element is popped. ["Foo Foo"] becomes [].

https://codesandbox.io/s/optimistic-cartwright-d14u6?file=/src/App.js

Please point me to the right direction.

Upvotes: 0

Views: 196

Answers (2)

bertdida
bertdida

Reputation: 5288

You are mutating the textArr when you do textArr.push(action.text). You should do

const TextEditorReducer = (textArr, action) => {
  switch (action.type) {
    case "append":
      // textArr.push(action.text);
      return [...textArr, action.text];
    case "undo":
      // textArr.pop();
      return textArr.slice(0, -1);
    default:
      throw new Error();
  }
};

Because your textArr is not a primitive data type, the changes you'll make to it inside TextEditorReducer will affect its value outside of that function.

Upvotes: 1

Andrej Jurkin
Andrej Jurkin

Reputation: 2256

State in React is meant to be immutable. This means the old value must stay unchanged at all times. In your case you are chaning the old value then returning a new one. That's a common source of errors. Try something like this instead:

const TextEditorReducer = (textArr, action) => {
  switch (action.type) {
    case "append":
      //textArr.push(action.text);
      return [...textArr, action.text];
    case "undo":
      //textArr.pop();
      return textArr.slice(0, -1);
    default:
      throw new Error();
  }
};

Upvotes: 1

Related Questions