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

108
Visualizações
Why state not updating in React?

I have a Alice-Carousel in react where I am getting the items from an API.After fetching the data from API , I am updating the items array for the carousel but am getting the value of items as undefined. CryptoState is the context to prevent prop-drilling.

import React from 'react'
import { useEffect ,useState} from 'react';
import { CryptoState } from '../CryptoContext'
import { TrendingCoins } from '../api';
import axios from 'axios'
import AliceCarousel from 'react-alice-carousel';
import {Link} from 'react-router-dom'

const Carousel = () => {
    const [trending,setTrending] = useState([]);
    const {currency,setCurrency} = CryptoState();
  
    useEffect(() => {
      const {data}= axios.get(TrendingCoins(currency));
      setTrending(data);
    },[currency,trending])
    
    // 0 pe 2 items dikhane hai, 512 size pe 4 items dikhane hai,
    // thats all about responsiveness.

    const responsives = {               
      0: {
        items: 2
      },
      512: {
        items: 4
      }
    }

    const items= trending.map((coin) => {
      return (
        <>
          <Link to={`/coins/${coin.id}`}/>
          <img 
             className="carouselImages"
             src={coin?.image}
             height="80"
             style={{marginBottom:10}}
          />
        </>
      )
    })

    return (
      <AliceCarousel
       infinite
       mouseTracking
       autoPlayInterval={1000}
       animationDuration={1500}
       disableDotsControls
       responsive={responsives}                     
       autoPlay
       items={items}
      />
    )
}

export default Carousel
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

useEffect(()=>{
const getData = async () => {
    try{
        const {data} = await axios.get(TrendingCoins(currency));
        setTrending(data);
    }catch{}
}
getData()
}, [currency, trending])

you are not waiting for the response, also you can just write async in useEffect arrow function

edit. : https://devtrium.com/posts/async-functions-useeffect

about 4 years ago · Juan Pablo Isaza Relatório

0

      const {data}= axios.get(TrendingCoins(currency));

the problem is axios.get is a async call so basically your are not waiting for its result, you could async/await or promises

    useEffect(async ()=>{
      const response = await axios.get(TrendingCoins(currency));
      setTrending(response.data);
    },[currency,trending])
about 4 years ago · Juan Pablo Isaza Relatório

0

Axios is asynchronous meaning the App needs to wait for the data to be delivered. One of the way to do this is by using Thenables.

There are some problems with the useEffect() dependecies. If you add trending as a dependency there will be an infinite loop that will probable make the browser crash. This is because the useState hook re-renders the component and changes the state and useEffect triggers when a dependency value changes.

In the return you also need to make changes. If the App does not have the available data, it cannot show it. To solve this we need use conditional statements.

Take a look

import React from 'react'
import { useEffect ,useState} from 'react';
import { CryptoState } from '../CryptoContext'
import { TrendingCoins } from '../api';
import axios from 'axios'
import AliceCarousel from 'react-alice-carousel';
import {Link} from 'react-router-dom'

const Carousel = () => {
    const [trending,setTrending]=useState([]);
    const {currency,setCurrency}=CryptoState();
  
    useEffect(()=>{
      axios.get(TrendingCoins(currency))
      .then((data) => {
          setTrending(data)
      })
      .catch((error) => {
          console.log(error)
      })
     
    },[currency])

    const responsives={         //0 pe 2 items dikhane hai, 512 size pe 4 items dikhane hai,thats all about responsiveness.
      0:{
        items:2,
      },
      512:{
        items:4,
      }
    }

    const items = trending.map((coin)=>{
      return (
        <>
        <Link to={`/coins/${coin.id}`}/>
        <img className="carouselImages"
        src={coin?.image}
        height="80"
        style={{marginBottom:10}}
        />
        </>
      )
    })

  if(trending === undefined) return (<p>Loading data....</p>)
  else return (
    <AliceCarousel
    infinite
    mouseTracking
    autoPlayInterval={1000}
    animationDuration={1500}
    disableDotsControls
    responsive={responsives}                 //responsive is to generate responsiveness....
    autoPlay
    items={items}
    />
  )
}

export default Carousel

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