reactjsreact-hooksuse-statereact-forms

React App crashes giving as useState input give an undefined error


I have create two states for my input elements and used onChange to manipulate their state. Why do I get this error even when I have declared the variables in a destructured array? Can someone explain to me what I am doing wrong please

import { React, useState } from 'react'

export const AddTransaction = () => {

  [transactionName, setTransactionName] = useState('');
  [amount, setAmount] = useState(0);

  return (
    <div>
        <h3>Add new transaction</h3>
        <form className="form">
            <div className="form-control">
            <label for="text">Transaction Name</label>
            <input 
              type="text" 
              className="text" 
              placeholder="Enter name of transaction" 
              value = {transactionName}
              onChange = {(e) => setTransactionName(e.target.value)}
            />
            </div>
            <div className="form-control">
            <label for="amount"> Amount </label>
            <input 
              type="number" 
              className="amount" 
              placeholder="Enter amount"
              value={amount}
              onChange = {(e) => setAmount(e.target.value)}
            />
            </div>
            <button className="btn">Add transaction</button>
        </form>
    </div>
  )
}

My app crashes with the below attached error -

Compiled with problems:X

ERROR


src\components\AddTransaction.js
  Line 5:4:    'transactionName' is not defined     no-undef
  Line 5:21:   'setTransactionName' is not defined  no-undef
  Line 6:4:    'amount' is not defined              no-undef
  Line 6:12:   'setAmount' is not defined           no-undef
  Line 18:24:  'transactionName' is not defined     no-undef
  Line 19:34:  'setTransactionName' is not defined  no-undef
  Line 28:22:  'amount' is not defined              no-undef
  Line 29:34:  'setAmount' is not defined           no-undef

Search for the keywords to learn more about each error.

Solution

  • Variables transactionName, setTransactionName, amount and setAmount are not declared. You can either use const or let to declare them.

    const [transactionName, setTransactionName] = useState('');
    const [amount, setAmount] = useState(0);
    

    Check: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment