Reputation: 508
I'm trying to update my regular React state through Immutable, and got into some few issues. The state isn't deeply nested or it isn't nested from anything other than the state itself, such as { "username" : "keyval" : null}}
This means I could not do something such as username.update('keyval', something)
, instead I need another approach. Its a rather easy question, I just don't know how to do it. Here's how my setState looks like, which I want to make an Immutable setState action.
handleUpdatePassword(event) {
event.persist()
this.setState(({password}) => ({
password: state.update('password', event.target.value)
})
);
}
And here is the error I get when trying:
handleUpdatePassword(event) {
event.persist()
this.setState({
password: state.update('password', event.target.value)
})
}
Also, This works, but I get this error: this.state.updater is not a function
handleUpdateUsername(event) {
console.log(this.state)
event.persist()
this.setState({
username: this.state.update('username', event.target.value)
})
}
Upvotes: 2
Views: 5872
Reputation: 28397
state
should be a plain JavaScript object as you can read in the documentation.
Note that state must be a plain JS object, and not an Immutable collection, because React's setState API expects an object literal and will merge it (Object.assign) with the previous state.
Your initial state should look something like this
constructor(){
...
this.state = {data: Map({ password: "", username: ""})}
}
After that, you'll be able to update the data like this
handleUpdatePassword(event) {
this.setState(({data}) => ({
data: data.update('password', password => event.target.value)
}));
}
Upvotes: 6
Reputation: 29906
You are creating explicit objects. Just let ImmutableJS do it for you.
class YourReactComp extends React.Component {
constructor() {
this.state = Immutable.Map({"username": ""});
}
handleUpdateUsername(event) {
console.log(this.state)
event.persist()
this.setState(this.state.set("username", event.target.value));
}
}
EDIT
ImmutableMap.update(key, updater)
uses a callback to set the value, you want ImmutableMap.set(key, newValue)
here.
Upvotes: 0