How to update or add an array in react.js?

Viewed 73

I'm using react native and my component is based on class base function. I'm facing difficulty in updating or adding object in an array..

My case :

I have an array:

this.state = {
     dayDeatil:[]
}

now i want to add an obj in it but before that i want check if that object exist or not.

obj = { partition :1, day:"sunday","start_time","close_time",full_day:false}

in condition i will check partition and day if they both not match. then add an object if exist then update.

here is function in which i'm trying to do that thing.

setTimeFunc =(time)=>{

    try{
    
      console.log("time.stringify() ")

      let obj = {
        partition:this.state.activePartition,
        day:this.state.selectedDay.name,
        full_day:false,
        start_time:this.state.key==="start_time"?time.toString():null
        close_time:this.state.key==="close_time"?time.toString():null
          }

      let day = this.state.dayDetails.filter((item)=>item.day===obj.day&&item.partition===obj.partition)

      if (day.length!==0) {
        day[this.state.key]=time.toString()
        this.setState({...this.state.dayDetail,day})

      } else {
        console.log("2")

        this.setState({
          dayDetails: [...this.state.dayDetails, obj]
        })
      }



      this.setState({ ...this.state, clockVisiblity: false });
    }
    catch(e){
      console.log("error -> ",e)
    }
  }
1 Answers

To check if the object exists or not, you can use Array.find() method, if it doesn't exists, the method will return undefined.

Now to update the state, the easier way would be to create a new array and set it as the new dayDetails state like this:

const { dayDetails } = this.state;

dayDetails.push(newData);

this.setState({ dayDetails: [...dayDetails] })

You should use the spread operator when setting the state because React uses shallow comparision when comparing states for a component update, so when you do [...dayDetails] you're creating a new reference for the array that will be on the state, and when React compares the oldArray === newArray, it will change the UI.

Also, after your else statement, you're updating the state with the state itself, it's good to remember that React state updates are asynchronous, so they won't be availabe right after the setState function call, this may be causing you bugs too.

Related