Iman Jalali
Iman Jalali

Reputation: 139

Refresh the page after adding the item to the array

there is an array with the default value and the item is added to the array using Delta, Table List When a row is added immediately the number of table rows returns to default, why?

App.js

import React, {Component, Fragment} from 'react';
import {TableData, RegForm} from './Layouts'


class App extends Component {
    state = {
        productList: [
            {id: 11, name: 'CD', price: '2000', describe: 'Educational'},
            {id: 24, name: 'Pen', price: '3500', describe: 'Design'},
            {id: 83, name: 'Pencil', price: '2500', describe: 'Design'}
        ],
    };

    handleDeleteByIndex = index => {
        const product = this.state.productList;
        product.splice(index, 1);
        this.setState({productList: product});
    };

    handleInsertToList = (e) => {
        const product = this.state.productList;
        product.push(e);
        this.setState({productList: product});

    };

    render() {
        const {productList} = this.state;
        return (
            <Fragment>
                <RegForm onInsertRow={this.handleInsertToList}/>
                <TableData rows={productList} onDeleteRow={this.handleDeleteByIndex}/>

            </Fragment>
        );

    }
}

export default App

Full code : enter link description here

Upvotes: 0

Views: 392

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12071

The page is refreshing due to the form submission, so everything is reset.

In Layouts/RegForm.js you need to prevent the default action of the form:

<form
  className={classes.root}
  noValidate
  autoComplete="off"
  onSubmit={(e) => {
    e.preventDefault() // <-- Add this
    props.onInsertRow({
      id: id,
      name: name,
      price: price,
      describe: describe
    });
  }}
>

I hope this helps.

Upvotes: 2

Related Questions