Append Item to Favorites

How to add a favorite item to a newly created list

I hacked something together here.
There are some improvements that can be made like adding typescript and less code, but I did make it so that you could follow along since I don't know the level of your coding skills.

and here is a codeSandbox link

import React, { useState } from "react";

const App = () => {
const [inputValue, setInputValue] = useState("");
const [items, setItems] = useState([]);

const addItem = () => {
const newItem = {
id: new Date().getTime(),
fav: false,
title: inputValue
};
setItems((oldState) => [...oldState, newItem]);
setInputValue("");
};

const makeFav = (id) => {
console.log("id prop", id);

const allItems = [...items];
const itemIndex = allItems.findIndex((item) => item.id === id);
allItems[itemIndex].fav = !allItems[itemIndex].fav;
setItems(allItems);
console.log("itemIndex", itemIndex);
};

return (
<div className="App">
<input
type="text"
placeholder="Add item"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button onClick={() => addItem()}>Add</button>
<hr />
<h2>Favorites</h2>
{items
.filter((item) => item.fav === true)
.map((item) => {
return (
<div key={item.id}>
{item.title}
<button onClick={() => makeFav(item.id)}>un fav</button>
</div>
);
})}
<hr />
<h2>list</h2>
{items
.filter((item) => item.fav === false)
.map((item) => {
return (
<div key={item.id}>
{item.title}
<button onClick={() => makeFav(item.id)}>fav</button>
</div>
);
})}
</div>
);
};
export default App;

How can i add a favorite item to a newly created list

The likedJokes array is an array of post ids updated from the button

<button onClick={() => addFavorite(id)} id="favori">
+
</button>

You can filter the postLists array for those having post ids in the likedJokes array, then map these to PostList components (assumes you are reusing the same component, looks like it in the expected screencap).

{postLists
.filter(post => likedJokes.includes(post.id))
.map((post) => (
<PostList
key={post.id}
linkin={post.linkin}
id={post.id}
title={post.title}
imageURL={post.imageURL}
photoURL={post.photoURL}
name={post.name}
addFavorite={addFavorite}
likedJokes={likedJokes}
setLikedJokes={setLikedJokes}
/>
))
}

Django - Add products to favorite list

You provide product.id to url product_favourite_list

<a href="{% url 'product_favourite_list' id=product.id %}">

So you should do:

<a href="{% url 'product_favourite_list' %}">

You can also adjust urlpatterns, but I guess it doesn't make sense because you are showing all favourite products of user.

If you should have id in product_favourite_list add it to the path:

path('favourites/<int:id>/', views.product_favourite_list, name='product_favourite_list'),

Also add id as argument to your view:

def product_favourite_list(request, id):
...

How to move item from item list to favorite list in React

You can try something similar,

function DummyComponent(){
const [fullList, setFullList] = useState(['item1', 'item2', 'item3', 'item4'])
const [favList setFavList] = useState([])

const handleFavAddClick=(e)=>{
setFavList(preState=>[...preState, e])
setFullList(preState=> preState.filter(item => item !== e))
}

return(
<div>
Full List (add to fav by clicking them)
<ul>
{
fullList.map(e=> <li key={e} onClick={()=>handleFavAddClick(e)}>{e}</li>)
}
</ul>

Fav List
<ul>
{
favList.map(e=> <li key={e}>{e}</li>)
}
</ul>
</div>
)
}

How i can add a saved items to favorite section in Flutter?

I'm gonna try to explain every required step, so bear with me.

First, you have to create a new list, which will be the list of favorite strings

  List<String> mainDataList = [
"Apple",
"Apricot",
"Banana",
"Blackberry",
"Coconut",
"Date",
"Fig",
"Gooseberry",
"Grapes",
"Lemon",
"Litchi",
"Mango",
"Orange",
"Papaya",
"Peach",
"Pineapple",
"Pomegranate",
"Starfruit"
];

List<String> favoriteDataList = [];

Now, as the body for your Scaffold, you have to add a TabBarView widgets, which contains a List of Widgets. The amount of widgets in this list, has to match with the amount of tabs that you have added in the TabBar, since, whenever you tap one of the tabs in it, it will move to the TabBarView's widgets that matchs the index.

So the body for your Scaffold should look something like this:

TabBarView(
children: [
ListView.builder(
itemCount: mainDataList.length,
itemBuilder: (context, index) {
return Card(
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Text(
mainDataList[index],
style: const TextStyle(fontSize: 19.0),
),
),
),
ElevatedButton(
onPressed: () {
setState(() {
favoriteDataList.add(mainDataList[index]);
});
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
Colors.deepPurple,
),
),
child: const Icon(
Icons.favorite,
color: Colors.white,
),
),
],
),
);
},
),
favoriteDataList.isEmpty
? const Center(
child: Text(
'There are no favorites yet!',
style: TextStyle(color: Colors.black),
),
)
: ListView.builder(
itemCount: favoriteDataList.length,
itemBuilder: (context, index) {
return Card(
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Text(
favoriteDataList[index],
style: const TextStyle(fontSize: 19.0),
),
),
),
ElevatedButton(
onPressed: () {
setState(() {
favoriteDataList
.remove(favoriteDataList[index]);
});
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
Colors.deepPurple,
),
),
child: const Icon(
Icons.remove,
color: Colors.white,
),
),
],
),
);
},
),
],
),

Of course, there is a lot of code there, I'm gonna split it in parts to explain it better.
As you may see, first we have two Widgets inside the children of the TabBarView, first one is the one that you had, there are some differences, since I've added a Row and inside it, a ElevatedButton, which will take care of adding the desired element to the favorite list:

ElevatedButton(
onPressed: () {
setState(() {
favoriteDataList.add(mainDataList[index]);
});
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(
Colors.deepPurple,
),
),
child: const Icon(
Icons.favorite,
color: Colors.white,
),
),

So, the important part of this button is the onPressed method, since you have built an StatefulWidget, we can tell that the state has been changed, using the setState method, it receives a function. Why do you need this? Because, you need a way to say the UI that the state has changed, so it has to rebuild.
For example, in an StatelessWidget, you don't have the setState method, so you won't be able to update the UI, without using some specifics Widgets or some specific state management solution (like BLoC).
Right now, when the user press this favorite button, we are going to add the selected item from the mainDataList to the favoriteDataList, making use of the index of the element that we have just pressed. And as I mentioned before, since the state was changed, the UI will rebuilt, so when you tap the favorite Tab, you will see that the selected item has been added.

The ElevatedButton in the second tab view, has some small differences

ElevatedButton(
onPressed: () {
setState(() {
favoriteDataList
.remove(favoriteDataList[index]);
});
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
Colors.deepPurple,
),
),
child: const Icon(
Icons.remove,
color: Colors.white,
),
),

Apart from a different Icon, Instead of being adding elements, we want to remove them, so whenever we press the button, the item positioned in the same index, will be removed from the favoriteDataList.

I have also used a ternary operator to display a widget if the favoriteDataList is not:

favoriteDataList.isEmpty
? const Center(
child: Text(
'There are no favorites yet!',
style: TextStyle(color: Colors.black),
),
)
: ListView.builder(

If is empty we display the Center... and if is not, the ListView...

And that's pretty much all, of course there some improvements to do on this code, for example, if you tap the same item in the first tab more than once, it will be added to the favorite list multiple times. But I think the example works, and you will be able to play with it and fix it!

Sorry for the long post, I hope it helps!



Related Topics



Leave a reply



Submit