I'm trying to add a state variable to another state variable.
Why am I doing this?
I'm using Firebase
as a database and storing my (relatively small amount of) data through state
in React
. I could use different variables for each "set" of data, but I'm trying to see if it is possible using a single variable.
So, I'm creating different state variables (here: child1
and child2
), and at the end storing them, or rather push
ing them into another state variable (here: parent
), and finally storing the state parent
using firebase only.
Here's what I have tried so far:
constructor() {
super();
this.addMember = this.addMember.bind(this);
this.state = {
parent: [],
child1: [],
child2: []
};
// const child1 = [0], child2 = [0];
// Tried using the above and below methods as well!
// const child1 = [];
// const child2 = [];
}
addMember(member) { // member has a property of name
switch (member.name) {
case `child1`:
this.child1 = [...this.child1].push(member) // this throws an error as it is unable to access "undefined"
break;
case `child2`:
this.setState({
child2: [...this.state.child2, member]
})
break;
default:
throw alert("something is reeeeeeally wrong")
// break;
}
let counter = {...this.state.parent}
counter[`${member.name}`].push(this.state.child2);
this.setState({ parent: counter})
}
The above code uses examples from other answers, which show how to store and access data within a nested object in a state:
React.js - What is the best way to add a value to an array in state
How to set a nested state in React
Accessing class variable declared in constructor in other parts of the app (React)