Home > Mobile >  Page is rendering the users after second submit
Page is rendering the users after second submit

Time:11-18

currently learning React and want to POST-Data to my Database and after the Post the table with all users should update automatically. Do you have any suggestion why it is not working?

I try to use the useEffect and add also the allData array, but it is then in an infinite loop. So currently it is just loading the page if I again press the submit button.

import React from "react";
import { useState, useEffect } from "react";
import axios from "axios";

const Form = () => {
  const [Username, setUsername] = useState("");
  const [Password, setPassword] = useState("");
  const [userList, setUserList] = useState([]);

  const allData = () => {
    axios.get("http://localhost:3001/api/alluser").then((response) => {
      console.log(response.data);
      setUserList(response.data);
    });
  };
  useEffect(() => {
    allData();
  }, []);

  const postdata = () => {
    axios.post("http://localhost:3001/api", {
      Username: Username,
      Password: Password,
    });
    allData();
  };
  const deletedata = (e) => {
    const users_id = e.target.id;
    axios.post("http://localhost:3001/api", {
      users_id: users_id,
    });
  };

  const clickHandler = (e) => {
    deletedata(e);
  };

  return (
    <>
      <label name="Username">
        <input
          onChange={(e) => setUsername(e.target.value)}
          type="text"
          name="Username"
          placeholder="Username"
        />
      </label>
      <label name="password">
        <input
          onChange={(e) => setPassword(e.target.value)}
          type="text"
          name="Password"
          placeholder="Password"
        />
      </label>
      <button onClick={postdata}>Submit</button>
      {userList.map((val) => {
        return (
          <>
            <li key={val.users_id}>
              {val.users_id}
              <button onClick={clickHandler}>
                Löschen
              </button>
            </li>
          </>
        );
      })}
    </>
  );
};

export default Form;

CodePudding user response:

allData() should wait until axios.post returns the response. You could use callbacks or async/await to achieve it.

  const postdata = async () => {
    await axios.post("http://localhost:3001/api", {
      Username: Username,
      Password: Password,
    });
    allData();
  };

or

  const postdata = () => {
    axios.post("http://localhost:3001/api", {
      Username: Username,
      Password: Password,
    }).then(() => { allData(); });
  };
  • Related