Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
How to get correct value with useState() in React?

I need to draw a filled star when item is in favourite. But now I have always blank star in the beginning (even if checkFav returns true).

Example: itemId is 5 checkFav returns true in its calling in isFav useState in jsx element isFav false

Result: not filled star, but on every click it changes correctly (so its adding and deleting to favourite list)

function CardPage() {
    const { itemId } = useParams();
    const [beer, setBeer] = useState([])

    useEffect(() => {
        const fetchData = async () => {
            const result = await axios(`https://api.punkapi.com/v2/beers/${itemId}`)
            setBeer(result.data[0])
        }
        fetchData();
    }, [itemId])

    const checkFav = () => {
        const icons = store.getState().favourite
        for (let i = 0; i < icons.length; i++) {
            if (icons[i].id === itemId) {
                return true                             //thats returning true
            }
        }
        return false
    }

    const [isFav, setIsFav] = useState(checkFav())

    const toggleFav = () =>{
        if (isFav === false) {
            setIsFav(true)
        } else {
            setIsFav(false)
        }
    }

    return (
        <div className="cardPage">
            <img src={beer.image_url} alt={beer.name} className="cardPage__image" />
            <div className="cardPage__content">
                <div className="cardPage__favourite" onClick={toggleFav}>
                    {isFav ? <i className={`pi pi-star-fill cardPage__star`} /> : //thats drawing like false
                       <i className={`pi pi-star cardPage__star`} />}
                </div>
            </div>
        </div>
    )
}

export default CardPage
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

if (icons[i].id.toString() === itemId) {

Converting the id to toString() will help you solve your query since you're also checking for type using ===.

about 4 years ago · Juan Pablo Isaza Relatório

0

useState in ReactJS is asynchronous, thus it takes certain milli seconds to update before which the component would have already been rendered. One approach I found working was to directly use the value returned from the methods rather than setState.

<div className="cardPage__favourite" onClick={toggleFav}>
   {checkFav() ? <i className={`pi pi-star-fill cardPage__star`} /> :
    <i className={`pi pi-star cardPage__star`} />}
</div>

Also once you set the isFav using setIsFav, you can use its value in other methods using the state variable isFav.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda