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

Viewed 1400

I was able to fetch data from an API and list them. I did that by watching videos. Now I want to add a button that says "add to favorite" for each item and by clicking on them I want to move the item from that list to favorite list. How can I achieve that? Please explain this in details cause I'm new in programing.

3 Answers

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>
  )
}

So, let's say you have two lists:

const [items, setItems] = useState([]);
const [favorites, setFavorites] = useState([]);

You can use this function to achieve what you want. If you want to completely move an item from items list to favorites, pass false as the second argument or don't pass it at all. But if you want to just copy the item to favorites list, pass true.

function moveToFavorites(id, copy) {
   setFavorites([...favorites, items.find(item => item.id === id)]);
   if(!copy) setItems(items.filter(item => item.id !== id));
}

Your list you received from the api is in the form of a JSON object. Depending on how the data was structured you may have the list in an array or its still flat.

Examples:

A)

List: {
name: "john",
},
{
name: "jane"}
}

B) List: {list: ["john", "jane"]}

Ideally you want option B. This means your list is in an Array. Look up documentation on how to convert JSON to an Array. There are great functions available to you in the lodash library which you can use.

Once your list in in an array you should be ready for adding and removing favorites. example:

let myList = ["john","jane"]

What you will want to do is have another array called favorites. When the user clicks on an item in the list, it will be added to their favorites array. You are removing from one array and another. Here is an example function.

let myList = ["john","jane"]; // list from api
let favorites = [] // your new list


//this function recieves the index (position) of the item the user clicked in the user interface

const addFavorites = (index) => {
  favorites.push(myList[index]) // adds items to favorites array
  myList.splice(index, 1); // removes same item from myList
  
}

// call the function
addFavorites(0) // will remove john
console.log(favorites)
console.log(myList)

}

Related