Home > Mobile >  Cannot read properties of undefined (reading 'preventDefault')
Cannot read properties of undefined (reading 'preventDefault')

Time:11-22

I need your help. I have a problem that I can't solve. I am new to this. I'm trying to send information to the backend. As a result, I get an error: Cannot read properties of undefined (reading 'preventDefault'). I want to ask, what is my mistake and is it correct that I am executing a POST request? Thank you

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

export let Form_Post = () => {
  let [name, setName] = useState('');
  let [price, setPrice] = useState('');
  let [description, setDescription] = useState('');

  let submitName = (e) => {
    setName(e.target.value);
  };

  let submitPrice = (e) => {
    setPrice(e.target.value);
  };

  let submitDescription = (e) => {
    setDescription(e.target.value);
  };

  let sendLaptop = (event) => {
    axios.post('http://localhost:8081/laptop', {
      name: name,
      price: price,
      description: description,
    });
    event.preventDefault();
    setName('');
    setPrice('');
    setDescription('');
  };

  useEffect(() => {
    sendLaptop();
  }, []);

  return (
    <form onSubmit={sendLaptop}>
      <input type="text" value={name} onChange={submitName} />
      <input type="text" value={price} onChange={submitPrice} />
      <input type="text" value={description} onChange={submitDescription} />
      <button onSubmit={sendLaptop}>Send</button>
    </form>
  );
};

CodePudding user response:

You're calling sendLaptop in your useEffect hook as well as on submit. When you do so, there is no event attached, and therefore event is undefined so event.preventDefault is also undefined.

CodePudding user response:

Looks like the problem is related to event.preventDefault() inside sendLaptop since it get's called from 2 places (useEffect & onClick handler).

Where the sendLaptop get called from useEffect, there is no event variable passed.

You should check if event is passed, and only then call it.

let sendLaptop = (event) => {
  axios.post('http://localhost:8081/laptop', {
    name: name,
    price: price,
    description: description,
  });
  if (event) {
    event.preventDefault();
  }
  setName('');
  setPrice('');
  setDescription('');
};
  • Related