bysiuxvx
bysiuxvx

Reputation: 75

Zustand: change value of parameter in stored object

I am trying to create a function for a state of rated movies in Zustand.

The state consists of an array of objects, example with two entries:

  ratedMovies: [
    { imdbID: "tt0076759", userRating: "5" },
    { imdbID: "tt0080684", userRating: "10" },
  ]

Below is the function managing ratedMovies changes. Here is where the issue lies. I want it to check whether an object with the same imdbID is present in ratedMovies state. And if so to update the value of it, instead of adding another object with the same imdbID but a new value.

If I try to change the rating of one of the movies from the above state example (with them in the state ofc), I get the IF console check and the app crashes with the error: TypeError: Cannot create property 'userRating' on number '0'

If the state is empty or I change the rating of other movies, I get the ELSE console check, but they are still not added into the state.

addUserRating: (rating) => {
    console.log("rating object", rating)
    set((state) => {
      if (state.ratedMovies.find((movie) => movie.imdbID === rating.imdbID)) {
        console.log("add rating IF")
        let index = state.ratedMovies.findIndex(
          (movie) => movie.imdbID === rating.imdbID
        )
        index.userRating = rating.userRating
        return [index, ...state.ratedMovies]
      } else {
        console.log("add rating ELSE")
        return [rating, ...state.ratedMovies]
      }
    })
  }

the onChange function on the input where one can rate a movie creates an identical object as in the state array and passes it to the function managing the state of ratedMovies:

  const changeUserMovieRating = (event) => {
    const movieRating = {
      imdbID: modalDetails.imdbID,
      userRating: event.target.value,
    }
    console.log(movieRating)
    addUserRating(movieRating)
  }

Output of which is:

{imdbID: 'tt0120915', userRating: '2'}

I hope i explained everything clearly, and I will highly appreciate any tips on how to solve this issue, thanks in advance!

Upvotes: 0

Views: 2568

Answers (1)

bysiuxvx
bysiuxvx

Reputation: 75

Sorry but this whole apprach I had at the time of asking this question had no sense and had to be reworked completely.

I decided not to add the parameter during the fetch, as in another component the same data could be fetched. So I decided to instead keep the value of the 'userRating' in the local storage and if the fetched movie was already once rated by the 'user', the value would be displayed.

Upvotes: 2

Related Questions