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

226
Visualizações
Component didn't render when I setState in useEffect

Why my component didn't do the render again when I setState inside my useEffect ? I read on google that the component is render another time if I setState inside the useEffect

My code :

export default function CarouselMusicGenres() {
    const [musicGenres, setMusicGenres] = useState(null)

    const setAllMusicGenres = () => {
        MusicGenresAPI.getAll()
            .then((response) => {
                if (response.status === 200) {
                    setMusicGenres(response.data.musicGenres)
                }
            })
            .catch((error) => {
                console.log(error)
            })
    }

    const displayAllMusicGenres = () => {
        if (musicGenres && musicGenres.length > 0) {
            musicGenres.forEach((musicGenre) => {
                return (
                    <SwiperSlide>
                        <Col
                            className="genre"
                            style={{
                                backgroundImage: `url(/assets/images/music-genres/${musicGenre.image_background_url})`,
                            }}
                        >
                            <span>{musicGenre.genre}</span>
                            <div className="transparent-background"></div>
                        </Col>
                    </SwiperSlide>
                )
            })
        }
    }

    useEffect(() => {
        setAllMusicGenres()
    }, [])

    return (
        <Row className="carousel-genres">
            <Swiper spaceBetween={10} slidesPerView={6}>
                {displayAllMusicGenres()}
            </Swiper>
        </Row>
    )
}

I try someting like that instead useEffect but still don't work

if (!musicGenres) {
        setAllMusicGenres()
}

Problem Fixed

I need to use map instead foreach to get the array returned and add return before my musicGenres.map

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

0

in order to return an array you should use map and you need to add something in your dependency array if you want to rerender on change. when you do it like that

useEffect(() => {
    setAllMusicGenres()
}, [])

you are only telling it to setAllMusicGenre on load and not on change , if you would like it to change when a certain change happens to musicGenres you should add it to the array.

useEffect(() => {
    setAllMusicGenres()
}, [musicGenres ])
about 4 years ago · Juan Pablo Isaza Relatório

0

you need to add dependency in order to Render it, again and again, for example, In your case musicGenres state will be your dependency so you need to write your useState Like below -

    useEffect(() => {
    setAllMusicGenres()
},[musicGenres])

It will update your component whenever you update musicGenres Note: You need to Pass Key(It should always be unique) also So DOM can Understand Something change and it will Update accordingly

When you write useEffect like given below in hooks -

useEffect(() => {
        setAllMusicGenres()
    }, [])

it will act Like componentDidMount

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