0

So I have been trying for days to solve the following issue:

movies [
{
     id: 1,
     name: 'Alpha',
     rating: 0
},
{
     id: 2,
     name: 'Bravo',
     rating: 0
},
{
     id: 3,
     name: 'Charlie',
     rating: 0
}
]

I already have a way to add and delete movies to/from this array but I want to have an input section for each item where the rating state will be updated to the input's value. I have been using 'useReducer' to assist with this but I guess I'm just not sure of the syntax/what would be the payload?

I know there is a way to do movies.map(movie=> {etc.etc.} but I can't seem to figure it out. Help is greatly appreciated.

EDIT:

<div>
{movies.map(movie => (
    <h1>{movie.name}</h1>
    <input placeholder={movie.rating}
    onChange={//I WANT THE MOVIE.RATING TO CHANGE ON INPUT CHANGE//}
    />
))}
</div>

I want the output to look something like this, where the state of the {movie.rating} object is updated on input change

2 Answers2

1

if you're using movies as component state you can pass this to your onChange function:

const updateRatingOnly = (id,rating) => {
    movies = movies.map(movie => {
      if(movie.id === id){
       return{...movie, rating}
      }
      return movie
    })

   setMovies(movies)

   //or

   this.setState({movies})
}
  • Thank you this helped a bunch! I ended up getting it to work by altering the code slightly ``` const handleRatingChange = (e, rating, id) => { setMovies(movies.map(movie => { if(movie.id === id) { return {...movie, rating: e.target.value} } return movie })) console.log(movies,rating,id) } ``` Thank you for the assistance though!! – TeflonTrout Aug 25 '20 at 00:40
0

You can do this easily by chaining the functions with the event. So your event handler will look like this:

const handleRatingChange = (movie) => ({target: {value}) => {
  //useReducer logic
  //movie = movie name
  //value = new rating
};
<div>
{movies.map(movie => (
    <h1>{movie.name}</h1>
    <input placeholder={movie.rating}
    onChange={handleRatingChange(movie.name)}
    />
))}
</div>
technicallynick
  • 1,562
  • 8
  • 15