How to Setstate array in React Native - reactjs

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

Related

Empty nested array when initializing state object

I've the following state initialised in a react app:
constructor(props) {
super(props);
this.state = {
meetings: [],
}
}
I need this.state.meetings to contain { Meetings: [] } until it is populated based on user action. How can i set this before the page renders?
The reason is that i have map functions running on this.state.meetings.Meetings and so i get an undefined error, which makes sense if the default is []. Rather than handle this in the code i wonder if i can just set Meetings: [] as a default value?
I would highly discourage you to store it as a nested structure. Keep it as flat as possible. So instead of directly setting the nested field Meetings inside state, just push or replace the data received from the api in the meetings field.
yourApiCall.then((response) => { // some pseudo code
this.setState({ meetings: response.Meetings });
});
Yeah, it's relatively simple, simply do
constructor(props) {
super(props);
this.state = {
meetings: {
Meetings: []
},
}
}
p.s. it also isn't good practice to have your object parent name be the same as a child :)
You can either do this.state = { meetings: { Meetings: [] } } because javascript is type free, this.state.mettings can assign to a [] later on.
Or a safer way:
// if meetings.Meetings is undefined, use empty array
const Meetings = this.state.meetings.Meetings || [].
//use Meetings to do stuff

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})
});
}

can't access object's properties within object in react

I can't seem to access data that's part of an object within an object. here I'm trying to access likes in profile which would otherwise be fine using vanilla javascript to print out this.state.data.profile.likes
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
var x = {
"notifications": 12,
"profile": {
"likes": 5
}
};
this.setState({
data: x
});
}
render() {
const {notifications, profile} = this.state;
return (
<div>
<span>Notifications {notifications}</span>
<span>Likes {profile.likes}</span>
</div>
);
}
Before mounting - and on the initial render - your state looks like this:
{
data: {}
}
After mounting - on the second render - your state looks like this:
{
data: {
notifications: 12,
profile: {
likes: 5
}
}
}
You're trying to access this.state.profile.likes which doesn't exist. Presumably you mean to access this.state.data.profile.likes which does exist, but only on the second render.
I noticed this while also trying to fix the same problem. The constructor should be:
constructor(props) {
super(props);
this.state = {
data: {
profile: {}
}
};
}
Always initialize objects within objects
https://reactjs.org/docs/react-component.html#mounting
render -> componentDidMount
put state data in constructor

Is Initializing state with props object causes mutation?

In my React application, one of the components needs state initialization from props.
Class ComponentA extends React.Component{
constructor(props){
this.state = {
objectA: props.objectA
}
}
someOnclickFunction(e){
let updatedObjA = this.state.objectA;
updatedObjA.value = e.target.value;
this.setState({
objectA: updatedObjA
})
}
}
In the above code snippet, props.objectA reference is copied to state. So, Am I mutating the props indirectly by updating the state?
Or setState() function will clone the object and keep new reference for the objectA?
class ComponentA extends React.Component {
constructor(props) {
super(props);
// state is null at this point, so you can't do the below.
// this.state.objectA = props.objectA
// instead, initialize the state like this:
this.state = {
objectA: props.objectA,
};
}
someOnclickFunction(e) {
// you can't set "objectA.value" like the following
// this.setState({
// objectA.value: e.target.value
// });
// you need to create a new object with your property changed, like this:
this.setState({
objectA: Object.assign({}, this.state.objectA, { value: e.target.value }),
})
}
}
This is a mistake that many beginners at react make. You can't simply update sub-properties of an object without consequences.. The following would also be wrong:
someOnclickFunction(e) {
var tmp = this.state.objectA;
// WRONG: don't do this either, you're modifying the state by doing this.
tmp.value = e.target.value;
this.setState({
objectA: tmp,
});
}
To elaborate on the correct way to do this using Object.assign.. this function takes all the parameters and merges them into the first element. So by providing a new object as the first parameter, you've created a copy of your first object with your new property.
Object.assign({}) // = {}
Object.assign({}, objectA) // = copy of objectA
Object.assign({}, objectA, { value: "newValue" }) // = copy of objectA with 'value' = 'newValue'.
Note: Object.assign() is a shallow clone, not a deep clone.

Update array object by specific index

How can I update groceries item(set completed to True) in my toggleGroceryCompleteness method?
I tried this.setState({groceries[groceryIndex]:{completed:true});
constructor(props) {
super(props);
this.state = {
groceries: [
{
name: "Apples",
completed: false
}
],
newGroceryName: ""
};
toggleGroceryCompleteness(groceryIndex) {
console.log(groceryIndex);
console.log(this.state.groceries[groceryIndex]);
}
Since you're editing the value of a previously set state, you should use this definition of setState
this.setState((prevState, props) => {
const newGroceries = prevState.groceries.slice()
newGroceries[groceryIndex].completed = true
return { ...prevState, groceries: newGroceries }
})
This takes the value of the groceries state array from before the setState call and assigns it to a new variable to be modified, accessing the given index and sets the completed property to true. Then returns a new object/state containing everything from the previous state value but a modified groceries property which is the new modified version.

Resources