Dmitry Chernyak
Dmitry Chernyak

Reputation: 305

Cannot read properties of undefined (reading 'preventDefault')

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>
  );
};

Upvotes: 0

Views: 1653

Answers (2)

felixmosh
felixmosh

Reputation: 35553

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('');
};

Upvotes: 1

Reuben Thompson
Reuben Thompson

Reputation: 350

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.

Upvotes: 1

Related Questions