What im trying to do is to not change the key of an item inside an array when the value is changed. So basically the user can update, delete or add a new language. To notice it In my code, I will have to add a key "added" (which means is a language added by the user when he created the account.) When the user adds a new language the array will look like this:
language:
[
{
added: "English"
},
"Italian" //the new language add by user when edit
]
parent.js
const [language, setLanguage] = useState([])
useEffect(() => {
axios
.get('api').then((response) => {
response.data.user.map((user) => {setLanguage([...language,{added:user.language)}))
}, [])
child.js
export default function child({language, setLanguage}) {
const handleAddClick = () => {
setLanguage([...language, ""]);
};
const handleItemChanged = (event, index) => {
const value = event.target.value;
const list = [...language];
console.log("list: ", list);
list[index] = value;
setLanguage(list);
};
}
So the problem is when the user updates the language that has the key added
, the key will disappear, and the array will look like this:
language:
[
"Englishhh", //updated
"Italian"
]
So I wanted the result like this:
language
[
{
added: "Englishhh" //updated
},
"Italian"
]
How can I solve it?
CodePudding user response:
Did you try this way before setting the language in handleItemChanged?
if(typeof list[index] !== 'string'){
list[index].added ? list[index].added = value : list[index].language = value;
}else{
list[index] = value;
}