Updating the value of an array of objects stored in Recoil js
Solution 1:
Use the following code :
import React from 'react';
import { useRecoilState, atom, RecoilRoot } from 'recoil';
const listState = atom({
key: 'listState',
default: [
{
id: 1,
title: 'test 1',
desc: '',
},
{
id: 2,
title: 'test 2',
desc: '',
},
{
id: 3,
title: 'test 3',
desc: '',
},
],
});
export default function App() {
return (
<RecoilRoot>
<TextInput />
</RecoilRoot>
);
}
function TextInput() {
let [list, setList] = useRecoilState(listState);
const onChange = (event, id) => {
let newList = [...list].map((item) => {
if (item.id === id) return { ...item, title: event.target.value };
else return item;
});
setList(newList);
};
return list.map((item) => (
<div key={item.id}>
<input
type="text"
value={item.title}
onChange={(e) => onChange(e, item.id)}
/>
<br />
Echo: {item.title}
</div>
));
}