Home > Software engineering >  Why state not updating in React?
Why state not updating in React?

Time:04-01

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

CodePudding user response:

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

CodePudding user response:

      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])

CodePudding user response:

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

  • Related