Referencing state from within state - React js - javascript

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}`}

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.

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)

Related

React Best Practices: Having properties other than `state` in a component

I'm reviewing a React Component and it contains a state property as well as an allData property.
To follow best practice, shouldn't allData be a part of state?
constructor(props) {
super(props);
this.allData = [];
this.state = {
allDisplayedData: [],
allRowsCount: -1,
favData: [],
favRowsCount: -1,
};
this.searchAll = this.searchAll.bind(this);
this.handleCellClick = this.handleCellClick.bind(this);
}
If you want the component to re-render on changing it, then it needs to be in state, otherwise put it wherever. Any instance variables other than this.state aren't part of React's control, so they don't have the same ability to set using setState. This means that they don't re-render the component like the state does.
Essentially, it depends on what you do with it and how you want to work with it.
I tend to use this pattern for things like cancelTokens and intervalIds and other data I might need later, but don't need as part of the state because it's only needed in unmount or update but not in the render itself.
If it's needed in the render, you should have it in state or be prepared to deal with the component not rendering when it's updated.
If you want to make the array part of state, then yes, if no, then no.
Other than the two previous detailed answers, I found the following statement at https://reactjs.org/docs/state-and-lifecycle.html
While this.props is set up by React itself and this.state has a
special meaning, you are free to add additional fields to the class
manually if you need to store something that doesn’t participate in
the data flow (like a timer ID).

What is the diff b/w this.name and this.state.name in react?

React has instance property and state property in react in constructor.
Instance property - Its not re-render the view. use to store the value.
State property - Its store and re-render the view.
Apart from above any other reason or difference or when should be use for both instance and state in constructor of React class component?.
Example:
class example extends Component{
constructor(){
this.state = {
name: 'albert'
};
this.name = 'albert';
}
}
When component state changes, it triggers component re-rendering (if it's not set to be ignored in shouldComponentUpdate()).
Changing instance property does not trigger re-rendering.
simple difference for both that is view part rendering.
EX: When State is update the view also update. Sometimes view is need not to reload that time we can store the value in component instance as you mentioned this.name.
Just check with below link to more about state and instance
https://medium.freecodecamp.org/where-do-i-belong-a-guide-to-saving-react-component-data-in-state-store-static-and-this-c49b335e2a00
It depends upon your requirement, which kind of data you are storing within it.
When any state variable is updated, react calls render to make changes in DOM element, so if you want to make any changes in DOM you should use state otherwise instance.
The current best practice is to use local state to handle the state of
your user interface (UI) state rather than data.
from this article
and instance properties when you just want to save some data to use in UI handling, calculations etc.
check this ref react-components-elements-and-instances for futher details
Whenever state is updated, react calls the render() method to update the DOM with required changes, and it should always be updated using setState(). The instance variable will be useful for block level manipulations which would then update the state if required. So if you want to re-render the DOM use state variables, else use instance variables.

how to avoid mutating this.state or redux object

For example, if I want to do any operation on this.state or some other object, such as Object.keys(this.state).map() to get access to all the values in the object.
Is it bad practice to do this?
Object.keys(this.state).map(k => this.state[k]);
Thanks
In React, you should only mutate this.state using this.setState() so that React knows when to re-render components.
The line of code you've written is fine, because you're not actually modifying the state object. You've already created a new array using Object.keys.
If however, you want to copy this.state without modifying it, try the following.
const state = {...this.state};
// Or
const state = Object.assign({}, this.state);
React Mutating State.
let state = {
age : 25,
name : 'Robin',
friends: ['Barney', 'Ted']
}
Change Age
this.setState({age: 26})
Change Name
this.setState({name: 'Lily'})
Add Friend
this.setState({
friends: this.state.friends.concat(['Marshall'])
})
Try this library immutability-helper for complex state updates.

Having trouble with setting state to value of "Enter name" field

I have a simple TextInput for entering your name. I want to pass this to another scene. First, though, I want to save the value to the state of the current component. When I open up the debugger, I get undefined for every console.log(this.name) I have.
Here is my code:
constructor(props) {
super(props);
this.state = {
name: ''
};
}
<TextInput style={styles.inputName}
placeholder="Enter your name"
textAlign="center"
onChange={this.handleChange.bind(this)} />
handleChange(event) {
this.setState({
name: event.nativeEvent.text
});
console.log(this.name)
}
Do you know why I am always getting "undefined" as the value of name? What is the proper way to set the state equivalent to what is being typed?
Is a better approach to set state only after the submit button is pressed? If so how is that done?
You're attempting to access this.name, which is checking for a (likely nonexistent) name property on the component object in your case. You should be looking at this.state.name. However, even if you did attempt to log out the updated state in your event handler via this.state.name, you would probably still run into problems. From the React docs:
setState() does not immediately mutate this.state but creates a
pending state transition. Accessing this.state after calling this
method can potentially return the existing value.
Finally, I would suggest extracting the name value from your event through event.target.value rather than going through the nativeEvent property.

do I have to use this.state in React to maintain component state?

I am unclear about the use of this.state in React components. While I can create this.state.myvar, why should not I just create this.myvar?
class MyComponent extends Component {
state = {myvar: 123};
render() {
return <span>{this.state.myvar}</span>;
}
}
or
class MyComponent extends Component {
myvar = 123;
render() {
return <span>{this.myvar}</span>;
}
}
I realize that there are helpers like this.setState, but at the end this.state is just a convenience, right? Or does it play a bigger role in React? Should I avoid setting properties directly on this to store my state? If so, why?
No, in fact; rather wrong.
this.state in a react component is a special React-backed container that is only acknowledged as having been updated when you use setState, which triggers a re-render, which might cause DOM updates (or not, depending on what React's diff algorithm sees happening in the JS virtual dom).
You can, of course, also use object properties bound to this, but changing them does absolutely nothing for the component itself. React doesn't look at your full component instance for changes, it only looks (internally) at the state, and (when changed by parents) at the props.
As such, you can't "create" things like this.state.myvar and then expect them to actually exist from lifecycle function to lifecycle function: as a special management construct, any values you tack onto state outside of proper this.setState(...) calls have undefined behaviour. They might exist, or they might not. If you really are working with the internal state, then you need to signal changes via this.setState({ myvar: value }).
Of course, that doesn't mean you can't use this.myvar, that'll work fine, but changing it will not "do" anything other than literally just that.
When would you use this.val instead of state? When your component has to perform operations that lead to an "intermediate" state, neither being one renderable state, nor the next. For instance, when code can update a state value multiple times between renders, during those changes your component is in an intermediate state, and so you don't want it to re-render. In fact, expecting it to can lead to huge bugs:
...
doTest() {
this.setState({ val: this.state.val+1 });
this.setState({ val: this.state.val+1 });
this.setState({ val: this.state.val+1 });
},
...
This code will not yield a this.state.val that's 3 higher than before, because state updates are queued, and overwrite each other. Only the last instruction before a re-render "wins". So in that case you'd need something like:
...
doTest() {
var localval = this.state.val;
localval++;
localval++;
localval++;
this.setState({ val: localval });
},
...
And then if we also need that value accessible outside of this function, then we finally have a legitimate use for a this property:
...
doTest() {
this.accessibleval = this.state.val;
this.updateValueAFewTimes();
this.setState({ val: this.accessibleval });
},
...
this.state plays a larger role than you realize.
Setting state via this.setState triggers the component to re-render (among other things). Otherwise, React would have no way of knowing when something it depends on changed.

Categories