Skip to content
Advertisement

not able to update state in reactsJs

i am using table input field to update state under map function to render it according to number of elements in the state.But when I used value={item.account} values are not updated in the state.which works fine when I use **value={accountCounter.account} where accountCounter is reactjs hook of type

const[accountCounter,setAccountCounter]=useState([
          { id: 1, account:"" ,accountOwner:""},
          { id: 2, account: "hi",accountOwner:"" },
          { id: 3, account: "bu" ,accountOwner:""}

And here is my rendering function

 accountCounter.map((item,key)=>{
  return(
    <tr key={key}>
    <td><input  type="text" value={item.account}
    name="account" onChange={(e)=>handleAccountCounter(e,item)}/></td>
    <td><input  type="text" value={item.accountOwner}
    name="accountName" onChange={(e)=>handleAccountCounter(e,item)}/></td>
    <td><span onClick={()=>deleteAccount(item.id)}>X</span></td>
    </tr>   
     )
  })}

here is my handleAccountCounter

const  handleAccountCounter=(event,counter)=>{
 const index = accountCounter.indexOf(counter);
 accountCounter[index][event.target.name]=event.target.value;
 setAccountCounter(accountCounter)
  }

But the state is not getting modified when in input field value={item.account}.dont know why..will you help me out

Advertisement

Answer

Use the previous state values to create a new array:

const App = () => {
  const [accountCounter, setAccountCounter] = useState([
    { id: 1, account: "", accountOwner: "" },
    { id: 2, account: "hi", accountOwner: "" },
    { id: 3, account: "bu", accountOwner: "" }
  ]);

  const handleAccountCounter = (event, counter) => {
    setAccountCounter((prevAccountCounter) => {
      const newCounter = [...prevAccountCounter];
      newCounter[prevAccountCounter.indexOf(counter)][event.target.name] =
        event.target.value;
      return newCounter;
    });
  };

  const deleteAccount = (id) => {
    setAccountCounter((prevAccountCount) =>
      prevAccountCount.filter((item) => item.id !== id)
    );
  };

  return accountCounter.map((item, index) => (
    <tr key={index}>
      <td>
        <input
          type="text"
          value={item.account}
          name="account"
          onChange={(e) => handleAccountCounter(e, item)}
        />
      </td>
      <td>
        <input
          type="text"
          value={item.accountOwner}
          name="accountOwner"
          onChange={(e) => handleAccountCounter(e, item)}
        />
      </td>
      <td>
        <span onClick={() => deleteAccount(item.id)}>X</span>
      </td>
    </tr>
  ));
};

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement