George Bleasdale
George Bleasdale

Reputation: 351

Referencing state from within state - React js

Is it possible to reference state from within state to create an id. e.g id = this.state.name + this.state.desc

Something like this?

this.state = {name:'', desc:'', id:`${this.state.name}-${this.state.desc}`}

Upvotes: 1

Views: 3416

Answers (2)

Toli
Toli

Reputation: 5777

Remember you need to set the state using setState

So

this.setState({ id:`${this.state.name}-${this.state.desc}` })

This is also assuming that you have already set the state in the constructor (or somewhere else int he app).

If you are in the constructor, then this should work just fine...

this.state = { name: 'Toli', desc: 'A programmer' };
this.state = {...this.state, id:`${this.state.name}-${this.state.desc}`}

I'm assuming you want to keep name and desc in the state so I'm copying them using the spread op (...this.state)

Upvotes: 1

Nathan
Nathan

Reputation: 636

Nope, that won't work. this.state is initialized before the constructor, but it won't like that you are referencing an undefined portion of the object. You would need to set it after initialization. I'm assuming you would be using this.state = {blah} from your constructor. Otherwise, you should use this.setState().

However this is also bad practice because anytime you update your name or desc, it will update the state again with your new id value. I don't know the full scope of your code, but you can probably just save the id to a function that gives you the string.

Upvotes: 3

Related Questions