Can I use state value again in state? - reactjs

i want to use index value for index_child, but this.state is undefined
state ={
index:0,
index_child:this.state.index
}
This code also fails.
state ={
index:0,
index_child:this.index
}

I dont know why you want to do that, but you can try something like this.
this.state = {
index:10,
get index_child () {
return this.index
}
};
console.log(state);

Related

Where to set state when I need that state in render?

I am getting this error below:
react_devtools_backend.js:2430 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
From the error, I know I am getting it because I am setting state in the render.
But I am not sure where to set the state because I need that state element, developerTitle further down inside the render method.
Where can I put it if not in render?
Thanks!
Here is my code:
export default class Game extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
developerTitle: ''
}
}
render() {
const { indieDeveloperId } = this.props;
this.setState({ developerTitle: this.getDeveloperTitle(game.indieDeveloperId) });
<div>
<h3>{this.state.developerTitle}</h3>
...
...
</div>
}
//by-indie-developer/{indieDeveloperId
async getDeveloperTitle(indieDeveloperId) {
const r = await axios.get(`/api/developer/by-indie-developer/${indieDeveloperId}`);
const developerTitle = r.data;
this.setState({
...this.state, ...{
developerTitle: developerTitle
}
});
}
}
You can't set a state in render(). But you can set a state when the component is loaded using the componentDidMount() function.
Add a function with that name like this to your component:
componentDidMount() {
this.setState({ developerTitle: this.getDeveloperTitle(game.indieDeveloperId) });
}
You dont have to call the function. The state will automatically be set.

React How to destruct deep props in constructor?

I have the following constructor in my class component:
constructor(props) {
super(props);
this.state = {
dirty: this.props.form.dirty // error happens here!
};
}
eslint returns an error for destructing the props. How is it possible for deeper props like this?
It is not a error per se. But you could use something like this to avoid the warning.
const { dirty } = props.form;
this.state = { dirty };
OR
const { form: { dirty } } = props;
this.state = { dirty };
First of all, don't use this.props inside constructor as you are getting props as an argument.
Secondly for destructuring, you could do something like this:
const {form: {dirty = 'any initial value in case of undefined'}} = props;
this.setState = {
dirty
}

How to Setstate array in React Native

How to set state field in array.
Below is my code:
constructor() {
super();
arrayCheck: [
isCheck = false
]
}
I want to get isCheck and then set state to true.
How can I set it?
Below is my function setState
onCheckBoxChange(isCheck, index, item) {
this.setState({........});
}
If you really want to update a state variable using array you can try this.
First, you need an array of object in state variable and update it like this
constructor () {
super();
this.state = {
arrayCheck: [
{ isCheck : false }
]
}
}
then update its value like this
onCheckBoxChange(isCheck, index, item) {
let arrayCheck = [...this.state.arrayCheck]
arrayCheck[0].isCheck = true
this.setState({
arrayCheck
})
}
First you need arrayCheck to be in the state object:
this.state = {
arrayCheck = [...]
}
Second, I would suggest using an object rather than an array. In array you can only access the index that holds the value.
With an object you may do something like:
constructor () {
super();
this.state = {
objectChecks: { // my also just set isCheck on the state
isCheck: false
}
}
}
And then when you want to change it:
this.setState({objectChecks: {isCheck: true}})
Hope it helps

react-native: How to setState() dynamic state in react-native?

I can create dynamic state like this example:
constructor(props) {
super(props);
this.state = {};
}
create state with this method:
func(name){
this.state[name];
}
and setState with this:
func2(name,value){
this.setState({[name]:value});
}
so with
this.func('color');
this.func('size');
I have this.func.color and this.func.size. right?
It works.
But I want something like this. I want create all new dynamic state in 'names' state.
constructor(props) {
super(props);
this.state = {names:[]};
}
names is a normal state.
func(name){
this.state.names[name];
}
func2(name,value){
this.setState({names:{[name]:value}:});
}
I call this functions:
func('color');
func('size');
func2('color','red');
func2('size','larg');
I expect with console.log(this.state.names) this:
{color:'red',size:'larg'}
But I get only {size:'larg'} (second function)
what is my wrong?
You're overwriting the value of names when you call this.setState again.
You're effectively doing:
this.setState({ names: { color: 'red' }});
this.setState({ names: { size: 'large' }});
Consider using Object.assign() in func2 to make sure you're not replacing the object you're trying to add properties to.
func2(name,value) {
this.setState({
names: Object.assign(this.state.names, {[name]: value})
});
}

Set initial state using local/session storage in react application

I want to initiate my state using local/session storage. Is this approach valid? I tried but it gives me an error. If not, then how can I retrieve a value from the storage directly to my state?
constructor(props) {
super(props);
sessionStorage.setItem('testkey','test value')
this.state = {
abc: sessionStorage.getItem('testkey')
}
}
The error is always undefined.
Also, if I use the other way around, below code works fine
constructor(props) {
super(props);
this.state = {
abc: this.getItems(val)
}
this.getItems = this.getItems.bind(this);
}
getItems(value){
let selectedItem = value;
return selectedItem;
}
But when I do this, it doesn't. I just cannot get the value from my session storage.
constructor(props) {
super(props);
this.state = {
abc: this.getItems(val)
}
this.getItems = this.getItems.bind(this);
}
getItems(val){
let setItem = sessionStorage.setItem('testkey', val);
let getItem = sessionStorage.getItem('testkey');
return getItem;
}
When I log getItem to my console, it gives me an object. What could possibly be the problem?
Im still not too sure what you mean but you definitely have to use this.setState().
this function accepts json {'key':'value'}
once set it updates the state.
You dont actually have to store a function within a state.
I dont know if this was a thing where you use getters and setters.
Set variable values using setState then retrieve them using this.state.[variable_name].
Hope this helps.
class Session extends Component {
constructor(props){
super(props);
this.setValue = this.setValue.bind(this);
this.state = {};
}
setValue(key, value){
let data = {};
data[key] = value;
this.setState(data);
}
render() {
let session = this.state.session;
return (
<div >
<div>{ session }</div>
<input onClick={ ()=> this.setValue('session','Hello') } type="button" value="Click Me" />
</div>
);
}
}
export default Session;
Happy coding.

Resources