Gautham Muralidharan
Gautham Muralidharan

Reputation: 157

reset array in react does not go to original state

After insert elements into the array, when I reset, it does not go to the initialStateOfList that is to [1,2,3,4,5].

For example, If I insert 6 and 7, then press on clear and then reset button, it goes to [1,2,3,4,5,6,7] and not [1,2,3,4,5].

What should I do to make it go back to the original state?

import React , {Component} from 'react';
import {render} from 'react-dom';

const initialStateOfList = [1,2,3,4,5];

class Form extends Component{

   state = {
    tempo : '',
    list : initialStateOfList
  };

  clearArray=()=>{
    this.setState({list:[]});
  }

  resetArray=()=>{
    this.setState({list:initialStateOfList});
  }

  tempAdd=(event)=>{
    this.setState({tempo:event.target.value});
  }

  addItem=(event)=>{
    event.preventDefault();
    this.state.list.push(this.state.tempo);
    this.setState({tempo:''});

  }

  render(){

    const listitem = this.state.list.map((number) =>  <li>{number}</li>);


    return(
      <div>
        <form ref="form" id="getInput" onSubmit={this.addItem}>
          {this.state.list.map((listItem)=><li>{listItem}</li>)}
          <input type="text" ref="formText" id="adder" onBlur={this.tempAdd} />
          <input type="submit" ref="formSubmit" id="passer" />
          <button id="clear" onClick={this.clearArray}>clear</button>
          <button id="reset" onClick={this.resetArray}>reset</button>

        </form>
      </div>
    );
  };
}

export default Form;

Upvotes: 1

Views: 3295

Answers (4)

Michael Yurin
Michael Yurin

Reputation: 1060

You can try to reset to the original state using a custom reset function:

import React, { Component } from 'react';

const getDefaultState = () => ({
  myArray: [1,2,3],
});

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { ...getDefaultState() };
  }

  componentDidMount() {
    this.setState({ myArray: [4,5,6] })
  }

  resetState = () => {
    this.setState({ ...getDefaultState() });
  };

  render() {
    return (
      <div onClick={this.resetState}>
        {JSON.stringify(this.state.myArray)}
      </div>
    );
  }
}

Upvotes: 1

tam.dangc
tam.dangc

Reputation: 2032

You mutated directly initialStateOfList with push at

this.state.list.push(this.state.tempo)

That cause the issue. You need to clone the array before mutating.

Have a lot of ways to clone an Object (Array is a type of Object) to avoid mutate directly.

const { list, tempo } = this.state // Should use Object destructuring for clean code

const newList  = Object.assign({}, list)  // Object.assign
const newList1 = [...list]                // Spread syntax
const newList2 = _.clone(list)            // `lodash` library

newList.push(tempo)
this.setState({list: newList, tempo: ''})

Upvotes: 0

Niraj Kaushal
Niraj Kaushal

Reputation: 1502

The reason is you are mutating list in state which is not allowed in react,

import React , {Component} from 'react';
import {render} from 'react-dom';

const initialStateOfList = [1,2,3,4,5];

class Form extends Component{

    state = {
        tempo : '',
        list : initialStateOfList
    };

    clearArray=()=>{
        this.setState({list:[]});
    }

    resetArray=()=>{
        this.setState({list:initialStateOfList});
    }

    tempAdd=(event)=>{
        this.setState({tempo:event.target.value});
    }

    //Read comment 
    addItem=(event)=>{
        event.preventDefault();
        // here you are mutating list in state, never do this in react instead you can use spread operator to create new array
        //this.state.list.push(this.state.tempo);
        const newList = [...this.state.list, this.state.tempo]
        this.setState({tempo:'', list: newList});
    }

    render(){
        const listitem = this.state.list.map((number) =>  <li>{number}</li>);

        return(
            <div>
                <form ref="form" id="getInput" onSubmit={this.addItem}>
                    {this.state.list.map((listItem)=><li>{listItem}</li>)}
                    <input type="text" ref="formText" id="adder" onBlur={this.tempAdd} />
                    <input type="submit" ref="formSubmit" id="passer" />
                    <button id="clear" onClick={this.clearArray}>clear</button>
                    <button id="reset" onClick={this.resetArray}>reset</button>

                </form>
            </div>
        );
    };
}

Upvotes: 0

Vrishank
Vrishank

Reputation: 364

I think you are getting confused here with const keyword. As the arrays in javascript are references, you are mutating the state.

When you declare const initialStateOfList with array, you will be freely able to add variables to this variable. "const" here means once declared you cannot re-assign that variable. But inside array, the elements can be changed.

e.g.

const arr1 = [1,2,3];
arr1.push(4); // Possible. No Error
arr1 = [1,2,3,4]; // Not possible.

So, every time you have to create new array and don't mutate the original array refernece.

Upvotes: 0

Related Questions