Home > database >  Using React, I want to save form inputs as object using state. Only one input is being recognized an
Using React, I want to save form inputs as object using state. Only one input is being recognized an

Time:07-10

Still pretty new to this, so pardon me if I don't have all the lingo down. I cannot figure out how to get the "fName" input to update the state of the "inputObj". What am I missing, because it seems like I am pretty close? Then again, I may be way off. I am just logging it to the console for now through the ListGamerData component. Thanks in advanced.

import {useState} from 'react';
import AddGamerData from './AddGamerData';
import ListGamerData from './ListGamerData';

const HandleForm = () => {
const [uNameArray, setUNameArray] = useState([]);
const [profileArray, setProfileArray] = useState([]);
const [inputObj, setInputObj] = useState("");

const checkUser = (event) => {
    event.preventDefault();
    if (uNameArray.includes(inputObj.uName) !== true) {
        setUNameArray([...uNameArray, inputObj.uName]);
        setProfileArray([...profileArray, inputObj]);
        setInputObj({fName: "", uName: ""});
    } else {
        alert("Gamer Tag already exists. Please try again.");
    }
}

const addUser = (event) => {
    checkUser(event);
};

return (
    <div className="handle-form-component">
        <h1>Gamer Data</h1>
        <p><strong>Enter gamer data below:</strong></p>
        <form onSubmit={addUser}>
            <AddGamerData inputObj={inputObj} setInputObj={setInputObj} />
        </form>
    <ListGamerData uNameArray={uNameArray} profileArray={profileArray} />
    </div>   
)}
export default HandleForm;

And here's the AddGamer component.

const AddGamerData = ({inputObj, setInputObj}) => {
const inputIsEmpty = () => inputObj.uName === "";

const handleChange = (event) => {
    setInputObj({[event.target.name] : event.target.value})
}

return (
    <div className="add-gamer-data-component">
        <input
            type="text"
            name="fName"
            placeholder="Enter First Name"
            value={inputObj.fName}
            onChange={handleChange}
        /><br></br>
        <input
            type="text"
            name="uName"
            placeholder="Enter Gamer Tag"
            value={inputObj.uName}
            onChange={handleChange}
        /><br></br>
        <button disabled={inputIsEmpty()} >Add Gamer</button>
    </div>
)}
export default AddGamerData;

CodePudding user response:

It's because of the handleChange function which overrides your object on every input change.

This change ensures that the old values of the state object are being carried over to the new state:

  const handleChange = (event) => {
    setInputObj((curr) => ({
      ...curr,
      [event.target.name]: event.target.value,
    }));
  };
  • Related