I have a collection of my lists in an array called allLists. When I create a new list I add the list to allLists array.
I can only add, update, delete elements from the selectedList.
My question is how do keep allLists updated with the changes made to selectedList.
- How do I update a single list in a collection of lists?
- Should I update using index of the array or by listName?
- Is it best to do this in a useeffect or should i trigger this in a react lifecycle event or is there other ways of doing this?
Codesandbox link: https://codesandbox.io/s/react-handle-lists-of-lists-92lez?file=/src/App.tsx
import { useEffect, useState } from "react";
import "./styles.css";
export interface ListInterface {
listName: string;
list: string[];
}
export default function App() {
const pokemonList = {
listName: "Pokemon",
list: ["Pikachu", "Onix", "Mew"]
};
const fruitsList = {
listName: "Fruits",
list: ["Apple", "Orange", "Banana"]
};
const numbersList = {
listName: "Numbers",
list: ["One", "Two", "Three"]
};
const [selectedList, setSelectedList] = useState<ListInterface>(numbersList);
const [allLists, setAllLists] = useState<ListInterface[]>([
pokemonList,
fruitsList
]);
const addListToAllLists = () => {
//Add new list to allList
if (selectedList?.listName !== "") {
setAllLists([...allLists, selectedList]);
}
};
const updateAllList = (listName: string) => {
allLists.forEach((list) => {
if (list.listName === listName) {
//set updated list
}
});
};
useEffect(() => {
if (selectedList) {
//addListToAllLists();
}
}, [selectedList]);
const addMultiElementToList = () => {
let newList = ["Four", "Five", "Six"];
setSelectedList({
...selectedList,
list: selectedList.list.concat(newList)
});
};
const addElementToList = () => {
let newElement = "New Element";
setSelectedList({
listName: selectedList.listName,
list: [...selectedList.list, newElement]
});
};
const changeSelectedList = (listName: string) => {
console.log("List", listName);
allLists.forEach((list) => {
if (list.listName === listName) {
console.log("Found List", listName);
setSelectedList(list);
}
});
};
return (
<div className="App">
<h2>Selected List [{selectedList.listName}]</h2>
{selectedList?.list?.map((element) => {
return <p>{element}</p>;
})}
<button onClick={() => addElementToList()}>Add Single Element</button>
<button onClick={() => addMultiElementToList()}>
Add Multiple Element
</button>
<button onClick={() => setSelectedList(numbersList)}>Clear List</button>
<hr></hr>
<h2>All Lists</h2>
<h4>Change Selected List</h4>
{allLists?.map((list) => {
return (
<button onClick={() => changeSelectedList(list.listName)}>
{list.listName}
</button>
);
})}
</div>
);
}