Cameron Bogucki
Cameron Bogucki

Reputation: 61

how to get my star rating component to set the ratingValue from 1-5

ive build a movie rating app where when you click on a star it sends a put request to change a value of the star

import axios from "axios";
import React, { useState } from "react";
import { FaStar } from "react-icons/fa";

const StarRating = (props) => {
    const [rating, setRating] = useState(props.rating);

    const starSwitch = (id) => {
        setRating(rating + 1);
        axios
            .put(`https://cjb-bbreviews.herokuapp.com/movie/${id}`, {
                ratingValue: rating,
            })
            .then((response) => {
                setRating;
                console.log("success", response);
            });
    };

    return (
        <div>
            {[...Array(5)].map((star, i) => {
                const ratingValue = i + 1;

                return (
                    <label>
                        <input
                            type='radio'
                            name='rating'
                            value={ratingValue}
                            onClick={() => starSwitch(props.movie_id)}
                            onMouseOver={() => setHover(ratingValue)}
                            onMouseOut={() => setHover(null)}
                        />
                        <FaStar
                            className='star'
                            color={ratingValue <= rating ? "#ffc107" : "#e4e5e9"}
                        />
                    </label>
                );
            })}
        </div>
    );
};
export default StarRating;
                        name='rating'
                            value={ratingValue}
                            onClick={() => starSwitch(props.movie_id, ratingValue)}
                            onMouseOver={() => setHover(ratingValue)}
                            onMouseOut={() => setHover(null)}
                        />
                        <FaStar
                            className='star'
                            color={ratingValue <= rating ? "#ffc107" : "#e4e5e9"}
                        />
                    </label>
                );
            })}
        </div>
    );
};
export default StarRating;

when i click the star it just incriments as one. star at a time instead of setting the star value i press. also the hover effect does not work.

Upvotes: 1

Views: 647

Answers (1)

AlpacaMax
AlpacaMax

Reputation: 479

That's because in starSwitch you just increment the rating by one with the line:

setRating(rating + 1);

You need to somehow let your onClick function know the new rating:

const starSwitch = (r, id) => {
    setRating(r);
    // Send PUT request
};

And in your input:

onClick={() => starSwitch(ratingValue, props.movie_id)}

Hope it helps.

Upvotes: 1

Related Questions