Home > other >  How to properly append records without replacing each other in reactjs
How to properly append records without replacing each other in reactjs

Time:06-04

I have some records in my database. The Code displays the first record on the table. When I want to append the second record to the first record via appendMore button. The second record displays the first record. Please how do properly append the second or the next to the first record. Here is my effort so far

import React from "react";
import axios from "axios";
import "./App.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      persons: [],
    };
    this.appendMore = this.appendMore.bind(this);
  }

  componentDidMount() {
    const url = "http://localhost/data/first_record.php";
    axios
      .get(url)
      .then((response) => response.data)
      .then((data) => {
        this.setState({ persons: data });
        console.log(this.state.persons);
        //alert(data);
        console.log(data);
      });
  }

  appendMore() {
    const url = "http://localhost/data/second_record.php";
    axios
      .get(url)
      .then((response) => response.data)
      .then((data) => {
        this.setState({ persons: data });
        // const persons = [...this.state.persons];

        console.log(this.state.persons);
        //alert(data);
        console.log(data);
      });
  }

  render() {
    //const { } = this.state;
    return (
      <div>
        <h1>Contact</h1>
        <table border="1" width="100%">
          <tbody>
            <tr>
              <th>id</th>
              <th>Name</th>
            </tr>

            {this.state.persons.map((contact, key) => (
              <tr key={key}>
                <td>{contact.id}</td>
                <td>{contact.name}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <span onClick={this.appendMore}>Append More</span>
      </div>
    );
  }
}

export default App;

CodePudding user response:

This will merge the two arrays as expected:

this.setState({ persons: [ ...this.state.persons, ...data ]})

Spread syntax (...) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

  • Related