skip to Main Content

I have a form with 3 fields, and I want to update useState value when user trying to input something, how I can pass identifier for each field as a string and then put it to a useState hook.
There I have Datepicker component and I’m passing second argument "date" to recognize which field should be updated but I can’t put it inside of a return state in handlerForm function…

import { useState } from "react";
import "./Expense.css";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export const NewExpense = () => {
  const [getShow, setShow] = useState(false);
  const [getForm, setForm] = useState({
    date: new Date(
      "Tue May 30 2023 00:00:00 GMT+0300 (Восточная Европа, летнее время)"
    ),
    title: "",
    price: "",
  });
  const handlerForm = (data, identifier) => {
    setForm((prev) => {
      let currentIdentifier = getForm[identifier];
      return { ...prev, currentIdentifier: data };
    });
  };
  const [startDate, setStartDate] = useState();
  return (
    <div className="newExpense">
      <form action="">
        <div className="group__input">
          <p>Date</p>
          <DatePicker
            selected={getForm.date}
            value={getForm.date}
            onChange={(data) => {
              handlerForm(data, "date");
            }}
          />
        </div>
        <div className="group__input">
          <p>Title</p>
          <input type="text" />
        </div>
        <div className="group__input">
          <p>Price</p>
          <input type="text" />
        </div>
        <div className="controls">
          <button type="button">Cancel</button>
          <button type="submit">Add</button>
        </div>
      </form>
      <div className="show__button">
        <button className="show__button">Show</button>
      </div>
    </div>
  );
};

I have tried to pass it with object.keys , and object[key] – and it doesn’t work

2

Answers


  1. You’re looking for this syntax (as explained in this MSDN article):

    const dynamicallyNamedKeyObject = { [keyName]: value };
    

    In your handler function this would look as follows:

    const handlerForm = (data, identifier) => {
        setForm((prev) => {
          let currentIdentifier = getForm[identifier];
          return { ...prev, [currentIdentifier]: data };
        });
      };
    
    Login or Signup to reply.
  2. When you are calling getForm[identifier] that returns the value, not the key.

    const handlerForm = (data, identifier) => {
        setForm((prev) => {
          return { ...prev, [identifier]: data };
        });
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search