Search code examples
javascriptreact-nativeobjectjavascript-objects

How to manage nested object with React Native State


I am trying to build a water reminder app. I have 4 screens and I am using react-navigation

  • Home (that I allow users to increase their amount drink that day and display how much water they drunk)
  • History (where user's water drinking history is displayed with graph and this is where I need nested object )
  • Notifications (where users defining with switch buttons if they want to receive notifications and when to receive)
  • Settings (where the user enters age, weight to determine how much they should drink daily). this is the first screen users see when they downloaded the app

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

Solution

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