I'm trying to get cookie data in use effect and then use that data, my component looks like this..
const Favourites = (props) => {
const [isClick, setClick] = useState(false);
const activityId = props.activityId
useEffect(() => {
const favourites = Cookies.get('favourites')
if (favourites[activityId] === true) {
setClick(true)
}
})
return (
<>
<div className="heart">
<Heart isClick={isClick} onClick={() => setClick(!isClick)} />
</div>
</>
);
}
this is what I get when I console.log(Cookies.get('favourites')) -
{"5edf47240dcb4713d3942e1b":true,"5edf47240dcb4713d3942e2b":true,"5fa10bd8f70458050ffe68af":true}
changing
const favourites = Cookies.get('favourites')
to
const favourites = {"5edf47240dcb4713d3942e1b":true,"5edf47240dcb4713d3942e2b":true,"5fa10bd8f70458050ffe68af":true}
produces the desired effect.
favourites is an array of activityID's stored in localstorage using js-cookie. it's basically a list of the users favourite activities, if they like the activity and click the heart button then the activityID is stored as the key and the value is set to true
the above doesn't work, setClick isn't being set to true if the activityId is true in the favourites array. If I console.log(Cookies.get('favourites')) and copy the result into const favourites then it does work
From your edit, it looks like what console.log
is showing is actually a string
. So, doing a JSON.decode
on what Cookies.get
is returning should do the trick:
const favourites = JSON.decode(Cookies.get('favourites'));