Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

305
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda