Home > Software engineering >  how i should use react hook useState with post axios
how i should use react hook useState with post axios

Time:10-22

I try call request post with hooks. Firstly, a call request post using this.setState and it working correctly but I want to use a hook (useState) instead of setState and it doesn't work

code below working correctly

export default class AddShoes extends Component {
  constructor(props) {
    super(props);
    this.state = this.startValue;
    this.state.show = false;
    this.shoesChange = this.shoesChange.bind(this);
  }

  startValue = {
    brand: "",
    model: "",
    date: "",
    price: "",
    img: "",
  };

  shoesChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  };

  submitShoes = (event) => {
    event.preventDefault();

    const shoes = {
      brand: this.state.brand,
      model: this.state.model,
      date: this.state.date,
      price: this.state.price,
      img: this.state.img,
    };

    axios.post("http://localhost:8080/api", shoes).then((response) => {
      if (response.data != null) {
        this.setState(this.startValue);
        alert("added")
      } 
    });
  };

the second code below doesn't work

export default function AddShoes() {
  const [values, setValues] = useState({
    brand: "",
    model: "",
    date: "",
    price: "",
    img: "",
  });
  // const [show, setShow] = useState(false);

  const handleSetInputs = (e) => {
    setValues({ ...values, [e.target.name]: e.target.value });
  };

  const submitShoes = (event) => {
    event.preventDefault();

    axios.post("http://localhost:8080/api", values)
    .then((response) => {
      if (response.data != null) {
        setValues(response.data);
        alert("added!");
      }
    });
  };

what I should change?

CodePudding user response:

To just change one property from an state-object in React Hooks you have to do this:

setValues(prevValues => ({ ...prevValues, [e.target.name]: e.target.value }));

CodePudding user response:

In the first example that works, you are resetting the state by calling this.setState(this.startValue)

In the second example, you are passing the result of the network request inside setValue setValues(response.data)

Create initialValues outside of AddShoes function component.

const initialValues = {
    brand: "",
    model: "",
    date: "",
    price: "",
    img: "",
  }

Now pass that into setValues inside submitShoes

  const submitShoes = (event) => {
    event.preventDefault();

    axios.post("http://localhost:8080/api", values)
    .then((response) => {
      if (response.data != null) {
        setValues(initialValues);
        alert("added!");
      }
    });
  };
  • Related