netchkin netchkin - 1 month ago 14
Javascript Question

Mutate string originating from React state

Let's say for some delicate reason I have the following react state:

{ superGreeting: 'Hello!!!' }


Now, assume I have this complicated operation that basically takes the superGreeting string and works on it, in the end replacing a character at a specific position. New state then should be:

{ superGreeting: 'Hullo!!!' }


So, there would be my action:

action = (index) => {
var { superGreeting: newGreeting } = this.state;
newGreeting[index] = 'u';
this.setState({superGreeting: newGreeting});
}


Unfortunatelly, such approach does not work and ends with:
TypeError: Cannot assign to read only property '1' of string 'Hello!!!'
, indicating this line as the offending one:
newGreeting[index] = 'u'


I use react.js, ES6, no redux, no mobx, no immutable.js. Thought that the issue is caused by the string still being related/used by the soon-to-be-previous state, so I thought that creating a copy would work (I tried
newGreeting = newGreeting.toString()
,
'' + newGreeting
, `${newGreeting}`,
''.concat(newGreeting)
, without any success). Any ideas?

Answer

Strings in JavaScript are immutable. Your example can be trimmed down to

(function(){
    "use strict";
    var str = 'Hullo!!!';
    str[1] = 'e';
})();

If you want to mutate a string, you'll need to create a new string, e.g.

(function(){
    "use strict";
    var str = 'Hullo!!!';
    str = str.slice(0, 1) + 'e' + str.slice(2);
})();
Comments