Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass object key from string to a return value in useState

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you are calling getForm[identifier] that returns the value, not the key.

const handlerForm = (data, identifier) => {
    setForm((prev) => {
      return { ...prev, [identifier]: data };
    });
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading