Wasteland
Wasteland

Reputation: 5379

React useEffect with an object

I'm trying to update a state. I have been reading that in order not to replace the state altogether, the spread operator needs to be used. It kinds of work as it appends to the previous state but I'm struggling in appending the state in the right place. The code below updates the state for 'categories' but it does it on the same level as 'all_categories' and 'current_category'. I'd like the fetched object to be put inside 'all_categories'. Thank you.

 const [ categories, setCategory ] = useState({
    all_categories: [],
    current_category: 'Cocktail'
  });
  const [recipes, setRecipe] = useState([]);

  useEffect(() => {
    Promise.all(
      [
        fetch(`https://the-cocktail-db.p.rapidapi.com/filter.php?c=${categories['current_category']}`, {
          "method": "GET",
          "headers": {
            "x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
            "x-rapidapi-key": "xxx"
          }
        }),
        fetch("https://the-cocktail-db.p.rapidapi.com/list.php?c=list", {
          "method": "GET",
          "headers": {
            "x-rapidapi-host": "the-cocktail-db.p.rapidapi.com",
            "x-rapidapi-key": "xxx"
          }
        })
      ]
    )
    .then(([response1, response2]) => {
      return Promise.all([response1.json(), response2.json()])
    })
    .then(([drinks_data, categories_data]) => {
      setRecipe(drinks_data['drinks'])
      setCategory(prev_state => {
        return {...prev_state, ...categories_data['drinks']};
      });
    })
    .catch(err => { console.log(err); });
  },[]);

Upvotes: 0

Views: 153

Answers (2)

shabeeb ck
shabeeb ck

Reputation: 131

Now you have 2 variable inside the categories (all_categories, current_category) and it you can update with setCategory function lets say if you want only update current category then it look like below

setCategory({...rest, {current_category: 'Vodka'}})

now you mutate the current_category object inside the categories state and rest remain same, the same way you can do rest of the variables inside the state, and if you try to mutate non existing variable then it ll create new variable inside the state,

let's see how you can add the response value from the api to the all_categories,

setCategory({...rest, {all_categories:[drinks_data]})

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281656

You have to update the all_categories key within category state and merge the individual category values using spread syntax like below

 setCategory(prev_state => {
    return {
       ...prev_state,
       all_categories: [
           ...prev_state.all_categories,
           ...categories_data['drinks']
       ]
    };
  });

Upvotes: 1

Related Questions