0

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); });
  },[]);

2 Answers 2

1

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']
       ]
    };
  });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Did you mean 'prev_state', not 'prevState'? Also, I get: Parsing Error: Unexpected token, expected ','
Sorry there were a couple of typos there. I updated my post. There was a closing bracket missing ] for the inner array
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.