L
L
lexstile2021-01-14 17:14:11
React
lexstile, 2021-01-14 17:14:11

How to properly edit a similar state in react?

There is this code:

const data = [
  { id: 1, value: "тест 1" },
  { id: 2, value: "тест 2" }
];

const [list, setList] = useState([]);

  const handleChangeItemValue = (id) => (e) => {
    const value = e.target.value;
    const index = list.findIndex((item) => item.id === id);
    const newList = [...list];
    newList[index].value = value;
    setList(newList);
  };

useEffect(() => setList(data), []);

  return (
    <div>
      {list.map((item) => (
        <label key={item.id} style={labelStyles}>
          <input
            style={inputStyles}
            value={item.value}
            onChange={handleChangeItemValue(item.id)}
          />
          <button onClick={handleClickRemoveItem(item.id)}>х</button>
        </label>
      ))}
      <button onClick={handleClickAddItem}>Добавить</button>
      <div style={valueStyles}>{renderItemValues()}</div>
    </div>
  );

Is it possible to edit it somehow differently and, maybe, to edit it more correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
abberati, 2021-01-14
@lexstile

const handleChangeItemValue =
  id =>
    ({ target: { value } }) =>
      setList(
        list => list.map(item => item.id === id ? { ...item, value } : item)
      )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question