I am trying to make a like/unlike button and for this purpose, I use a react hook name liked
initialised to false
.
this hook is used to modify the like button in front and the like event in back-end.
The problem is that setState is an asynchron function and I cannot have the good state of liked
to perform my actions.
I already tried with a useEffect
but with liked
initialised to false
, the action when liked === false
is performed on loading. I don t want to.
here is my code
import React from 'react'
import styled from 'styled-components'
import HeartIcon from 'client/components/icons/Heart'
import IconButton from 'client/components/IconButton'
const Heart = styled(HeartIcon)`
stroke: ${p => p.theme.primary};
stroke-width: 2;
fill: transparent;
transition: fill 300ms;
display: block;
width: 100%;
height: auto;
&[aria-checked='true'] {
fill: ${p => p.theme.primary};
}
`
export default function LikeButton(props) {
const [liked, setLiked] = React.useState(false)
function onLikeChange() {
setLiked(prevLiked => !prevLiked)
if (liked === true) {
// creation d'un event like
console.log('like')
} else {
console.log('unlike')
// destroy l'event du like existant
}
}
return (
<IconButton onClick={onLikeChange} {...props}>
<Heart aria-checked={liked} />
</IconButton>
)
}
of course I can switch my actions to perform what I want but I prefere to understand what I'm doing because I'm new to react ;)
What is the way ? Thank you