==== neues Thema ====
==== 13. Februar 2024 Aufgaben ====
-------------------------------------------------------
1) // TO-DO Setze player name to "Bob" //
const [game, setGame] = useState({
id: 1,
player: {
name: 'John',
},
});
-------------------------------------------------------
2) // TO-DO: Neues Topping dem toppings Array hinzufügen //
const [pizza, setPizza] = useState({
name: 'Spicy Pepperoni',
toppings: ['Mushroom'],
});
-------------------------------------------------------
3) // TO-DO: Ändere quantity des Produkts mit id 2 zu 2 //
const [cart, setCart] = useState({
discount: 0.1,
items: [
{ id: 1, title: 'Product 1', quantity: 1 },
{ id: 2, title: 'Product 2', quantity: 1 },
],
});
-------------------------------------------------------
===== Code Notizen ======
const [bugs,setBugs] = setState(
{id:1, titel: 'Bug1', fixed: false}
{id:2, titel: 'Bug2', fixed: false}
);
setBugs([...bugs].map((bug) => (bug.fixed === false ? {...bug, fixed: true}: bug )));
//setBugs(bugs.map((bug) => (bug.fixed === false ? {...bug, fixed: true}: bug )));
// setBugs(bugs.map(bug) => (bug = (bugs.id === 2 ? {...bug,fixed = true} : bug ) ) )
setBugs(bugs.map(bug) => (bug = {...bug,fixed: true})
setUser({...user,adress: {...user.adress, zipCode: 94112}});
==== nachschauen.txt ====
// Updating Arrays
const [mood, setMood] = useState(['happy', 'cheerful']);
console.log(mood);
const handleCLick = () => {
// Neues Array item hinzufügen
mood.push('sad'); // Tu das nicht! Es verändert das original Array
setMood([...mood, 'sad']);
// Item aus Array entfernen
setMood([...mood].filter((mood) => mood !== 'happy'));
// Update Item in Array
setMood(mood.map((mood) => (mood === 'sad' ? 'blub' : mood)));
};
// Updating Objects
const [cocktail, setCocktail] = useState({
title: 'Old Fashioned',
price: 7,
});
console.log(cocktail);
const handleClick = () => {
cocktail.price = 8; // nicht tun!
setCocktail(cocktail); // funktioniert nicht
const newPrice = {
title: cocktail.title, // spread cocktail object
price: 9,
};
setCocktail(newPrice);
// oder
setCocktail({ ...cocktail, price: 9 });
};
// Updating nested Objects
const [user, setUser] = useState({
name: 'John',
lastName: 'Doe',
address: {
city: 'San Francisco',
zipCode: 94111,
},
});
console.log(user);
const handleCLick = () => {
setUser({ ...user, address: { ...user.address, zipCode: 94112 } });
};
// Updating Object Arrays
const [bugs, setBugs] = useState([
{ id: 1, title: 'Bug 1', fixed: false },
{ id: 2, title: 'Bug 2', fixed: false },
]);
console.log(bugs);
const handleCLick = () => {
// Update Props in Array
setBugs(bugs.map((bug) => (bug.id === 2 ? { ...bug, fixed: true } : bug)));
};