I have a recipe app and i implemented a star rating, i have to save the value in local storage and display the average rating value.I updated the code after reading the answers in order to get the recipe id and the rating in the local storage and it kinda works.Using console log i was able to see that the rating and the id showing good but nothing is saving in the local storage and i don't understand why any help?
This is the code:
import styled from "styled-components";
import Searched from "../Pages/Searched";
import { useParams } from "react-router-dom";
const StarRating = () => {
let params = useParams();
const [details, setDetails] = useState({});
const [activeTab, setActiveTab] = useState("instructions");
const fetchDetails = async () => {
const data = await fetch(
`https://api.spoonacular.com/recipes/${params.name}/information?apiKey=${process.env.REACT_APP_API_KEY}`
);
const detailData = await data.json();
setDetails(detailData);
console.log(detailData);
};
useEffect(() => {
fetchDetails();
}, [params.name]);
const [rating, setRating] = useState(0);
const [hover, setHover] = useState(0);
useCallback(() => {
const data = localStorage.getItem("rating");
if (data) {
data[details.id] = rating;
localStorage.setItem("rating", JSON.stringify(data));
} else {
localStorage.setItem("rating", JSON.stringify({ [details.id]: rating }));
}
}, [rating]);
return (
<StarStyle>
<div className="star-rating">
{[...Array(5)].map((star, index) => {
index += 1;
return (
<button
type="button"
key={index}
className={index <= (hover || rating) ? "on" : "off"}
onClick={() => setRating(index)}
onMouseEnter={() => setHover(index)}
onMouseLeave={() => setHover(rating)}
>
<span className="star">★</span>
</button>
);
})}
</div>
</StarStyle>
);
};
export default StarRating;
const StarStyle = styled.form`
button {
background-color: transparent;
border: none;
outline: none;
cursor: pointer;
block-size: 150px;
font-size: 60px;
}
.on {
color: #000;
}
.off {
color: #ccc;
}
`;