1

I want to receive the value of some input fields and set them as the newValue state, but some of the attributes of the state are objects themselves. The format in which I want newValue state to be :

{
        name : {
            firstName : 'Eithan',
            lastName :'Auralius'
        },
        rank : 7
}

Right now, the object is getting saved like :

{
    name.firstName : 'Eithan',
    name.lastName : 'Auralius',
    rank : 7
}

Is there a way to achieve this by tweaking the getValue function or the input field?

//State to store the created or updated user string
const [newValue, setNewValue] = useState();

//onChange triggered function to update 
const getValue = (event)=> {
    
    //Setting the value of the state using the changed input fields
    setNewValue((newValue)=> {
        return {
            ...newValue,
            [event.target.name] : event.target.value,
        }
    });
}

const submitData = (event)=> {
    event.preventDefault();
    console.log(newValue);
}

return (
    <div className='loginRegister'>
        <form onSubmit={submitData}>
            <div className='descriptionInput'><div className='description'>First Name</div>
            {//the name prop is used to set the field name in the getValue function}
            <input type="text" name='name.firstName' defaultValue={member.name.firstName} onChange={getValue}></input></div>
            <button>Submit</button>
        </form>
    </div>
);
Debopam77
  • 15
  • 3

1 Answers1

0

You can try this.

import { useState } from "react";

export default function App() {
  let defaultState = {
    name: {
      firstName: "",
      lastName: ""
    },
    rank: 0
  };
  const [newValue, setNewValue] = useState(defaultState);

  const submitData = (event) => {
    event.preventDefault();
    console.log(newValue);
  };
  //onChange triggered function to update
  const getValue = (event) => {
    //Setting the value of the state using the changed input fields
    setNewValue((newValue) => {
      return {
        name: {...newValue.name, [event.target.name]: event.target.value},
        rank: newValue.rank
      };
    });
  };

  return (
    <div>
      <form onSubmit={submitData}>
        <div>
          <div>First Name</div>
          <input
            type="text"
            name="firstName"
            defaultValue={newValue.name.firstName}
            onChange={getValue}
          ></input>
        </div>
        <button>Submit</button>
      </form>
    </div>
  );
}
Ayaz
  • 2,111
  • 4
  • 13
  • 16
  • Thanks for the reply, but I had multiple such attributes like 'name' which were objects. Had to go for an uglier solution : `if(elementName.includes('.')) { const part = elementName.split('.'); result[part[0]][part[1]] = elementValue; }` – Debopam77 May 01 '21 at 12:54