1

Trying to add an object into an array within the state of this component, unable to concat the new object to array without a 'property undefined' error.

I have been able to get this to work with a 'shallow' state with an array but would like to have , would prefer to have it work with separate array inside.

The state

    constructor(props) {
      super(props);
        this.state = {
          show: false,
          id: null,
          name: 'New Task',
          timerOn: false,
          seconds: 0,
          minutes:0,
          hours:0,
          complete: {
            todayId: null,
            list: []
          }
        }
      }

Method for updating state, making a copy of the 'controls' (minutes, seconds, start etc) resetting the state back to it's initial values taking a copy of the state and applying it to the array:

    completeTaskHandler = () => {
      if (this.state.seconds === 0 && this.state.minutes === 0 && this.state.hours === 0) {
        alert('Please Provide a name');
      }
      else {
        const end = new Date();
        let finishedTask = new Object ({
          start: this.state.id,
          end: end,
          name: this.state.name,
          seconds: this.state.seconds,
          minutes: this.state.minutes,
          hours: this.state.hours,});

        this.setState((prevState,props) => {
          return {
            start: null,
            show: false,
            id: null,
            name: 'task',
            timerOn: false,
            seconds: 0,
            minutes:0,
            hours:0,
            complete: prevState.complete.list.concat(finishedTask)
          }
        });
        clearInterval(this.interval);
      }
    }
3
  • Can you give more clarity to help , Please? Commented Sep 6, 2018 at 16:30
  • Try to log 'prevState.complete.list' and see if it's the object you expect it to be (an array) Commented Sep 6, 2018 at 16:31
  • Since list is an array. Change to complete: [...prevState.complete.list, finishedTask] Commented Sep 6, 2018 at 16:39

1 Answer 1

1

You are doing concat on an array. Since list is an array.

Use previous state to push new value to an array. Check below solution for better understanding

  this.setState((prevState,props) => {
      return {
        start: null,
        show: false,
        id: null,
        name: 'task',
        timerOn: false,
        seconds: 0,
        minutes:0,
        hours:0,
        complete: [...prevState.complete.list, finishedTask]
      }
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.