简体   繁体   中英

Update state after axios POST request

I am pretty new to React and I have created a CRUD on the Backend (Express) and I want to bind it to a React Frontend. I have a form that allows adding users, and I want the state to be updated when a user is added successfully. I managed to get it up and running by implementing a "document.createElement" and a page refresh after 5 seconds (with setTimeout). I'm thinking how can I make the component rerender(update state) once the POST is successful.

Here is what I've managed so far:

class App extends Component {
  constructor() {
    super();
    this.state = {
      users: null
    };
  }

  componentDidMount() {
    axios
      .get("http://localhost:3000/customer_all")
      .then(res => {
        console.log(res);
        this.setState({ users: res.data });
      })
      .then(() => console.log(this.state.users.map(item => item.name)))
      .catch(err => console.log(err));
  }

  submit(e) {
    e.preventDefault();
    var form = document.forms[0];
    var data = {};
    var para = document.createElement("p");
    para.textContent = "Success";
    var id = document.getElementById("message");

    data.name = form.name.value;
    data.email = form.email.value;
    axios
      .post("http://localhost:3000/customer", {
        name: data.name,
        email: data.email,
        headers: {
          "Content-Type": "application/json"
        }
      })
      .then(response => {
        id.appendChild(para);
        setTimeout(() => window.location.reload(), 5000);
        form.reset();
      })
      .catch(err => console.log(err));
  }

  render() {
    return (
      <div>
        <div id="message" />
        <form method="POST" onSubmit={this.submit}>
          <label htmlFor="name">Nume </label>
          <input type="text" name="name" /> <br />
          <br />
          <label htmlFor="email">Email </label>
          <input type="email" name="email" required />
          <input type="submit" value="Adauga" />
        </form>
        <ol>
          {!this.state.users
            ? "loading"
            : this.state.users.map((item, i) => <li key={i}>{item.name}</li>)}
        </ol>
      </div>
    );
  }
}

Thanks in advance for any hint!

In the submit method add the new user in the array and setState.

submit = (e) => {
e.preventDefault();
var form = document.forms[0];
var data = {};
var para = document.createElement("p");
para.textContent = "Success";
var id = document.getElementById("message");

data.name = form.name.value;
data.email = form.email.value;
axios
  .post("http://localhost:3000/customer", {
    name: data.name,
    email: data.email,
    headers: {
      "Content-Type": "application/json"
    }
  })
  .then(response => {
    const {users} = this.state;
    users.push(response.data);
    id.appendChild(para);
    this.setState({users});
    form.reset();
  })
  .catch(err => console.log(err));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM