I am trying to build a water reminder app. I have 4 screens and I am using react-navigation
I have state in my apps such as drunk, goal etc. Everyday I am setting drunk value to zero that users can start over again.
What I have done is that I have created new state called object and set it to empty object. And I was able to update history state as below with state handler function.
handleHistory = () => {
let currentDateString = moment().format('DDMMYYYY');
this.setState(
{
history: {
...this.state.history,
date: currentDateString,
drunk: this.state.drunk,
goal: this.state.goal,
progress: this.state.progress,
},
});
};
//this is what I get
Object {
"date": "20052019",
"drunk": 136,
"goal": 82,
"progress": 1.6585365853658536,
}
What i need is that nested object with dates with keys as date
history: {
"20052019": {
"date": "20052019",
"drunk": 136,
"goal": 82,
"progress": 1.6585365853658536,
},
"21052019": {
"date": "21052019",
"drunk": 82,
"goal": 82,
"progress": 1.0,
}
}
You can dynamically access/create keys using object[key]
.
handleHistory = () => {
const currentDateString = moment().format('DDMMYYYY');
const { history, drunk, goal, progress } = this.state;
this.setState({
history: {
...history,
[currentDateString]: {
...history[currentDateString],
date: currentDateString,
drunk, goal, progress
}
}
});
};