Shivam
Shivam

Reputation: 103

how to update value in reactjs

    constructor(props) {
        super(props)

        this.state = {
            isEdit: false,
            currentProduct : {
                sku: '',
                productName: '',
                description: '',
                duration: '',
            },
        }       
    }    

handleChange = (e) => {
            this.setState({
              currentProduct: {
               ...this.state.currentProduct,
               [e.target.name]: e.target.value
              }
          })
       }

    clickHandle = (e) => {
        e.preventDefault()
        const currentProduct = {...this.state.currentProduct}
        currentProduct.id = this.props.match.params.id

        this.props.updateProduct(currentProduct)
        this.props.history.push('/')
    }

When updating field it updates the values but when i goes again to update single value it update only that and removes the other don't know why

Upvotes: 0

Views: 42

Answers (2)

Ayyappa Gollu
Ayyappa Gollu

Reputation: 966

you are not destructuring entire state first. so do ...state. otherwise isEdit field will be lost.

  handleChange = e => {
    this.setState({
      ...this.state,
      currentProduct: {
        ...this.state.currentProduct,
        [e.target.name]: e.target.value
      }
    });
  };

Upvotes: 0

akhtarvahid
akhtarvahid

Reputation: 9769

handleChange = (e) => {
        this.setState({
           ...this.state.currentProduct,
           [e.target.name]: e.target.value
      })
   }

Upvotes: 2

Related Questions