abhishek narayan
abhishek narayan

Reputation: 139

Getting TypeError: Object(...) is not a function error when trying to change a state property

I am very new to React and trying to implement the Rating feature in the code. Can anyone tell, why I am Getting TypeError: Object(...) is not a function error when trying to change a state property when the Rating component onChange property is set.

My code

export default function Details(props) {

const [movie_detail, set_movie_detail] = useState({
    poster_url:"",
    artists:[],
    title:"",
    genres:[],
    duration:0,
    release_date:"",
    rating:0,
    storyline:"",
    id:"",
    wiki_url:"",
    trailer_url:"",
    censor_board_rating:""
  });

    async function data(){
        const data = await fetch(props.baseUrl + "movies/"+props.match.params.id ,
        {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                "Cache-Control": "no-cache"
            }
        });
        const rawData = await data.json();
        set_movie_detail(rawData);
    }

    const handleRatingChange = (value) =>{
        console.log(value);
        setState({rating:value});
    }

    useEffect(() => {
        data();
    }, []);

  return (
    <>
      <Header baseUrl={props.baseUrl} movieid={movie_detail.id} ></Header>
        .........

        <div className="column3">
          <Typography>
            <b>Rate this movie</b>
          </Typography>
          <Rating
            name="rating"
            value={movie_detail.rating/2}
            max={5}
            onChange={handleRatingChange}
            icon=
                {
                    <StarBorderIcon 
                    style={{color:"black"}}
                    />
                }
            /> 
      </div>
    </>
  );
}

Upvotes: 0

Views: 1712

Answers (2)

Prajwal Kulkarni
Prajwal Kulkarni

Reputation: 1705

You should be using set_movie_detail instead of setState whilst trying to update the state value.

const handleRatingChange = (value) =>{
        console.log(value);
        set_movie_detail(prev=>{...prev,rating:value});
}

set_movie_detail is the function that updates the state of movie_detail. Here, we are making use of the spread operator ... to ensure that only the desired attribute(s) (rating here) is overwritten and the rest of the values remain the same.

Upvotes: 1

Houssam
Houssam

Reputation: 1877

You should be using the correct name of the function that updates the state. In this case set_movie_detail instead of setState. You should also merge the update with the previous state instead of overwriting it.

Your function should be as follow:

const handleRatingChange = (value) => {
  console.log(value);
  set_movie_detail((prevState) => { ...prevState, rating: value });
}

Upvotes: 2

Related Questions