'React JS State late Update

I recently started doing React JS but facing one Problem. I use bootstrap flat icons in my component. I have two APIs one for the product list and the second for the wish list I have to compare both API results. if the product is present in the wishlist then I have to show the heart icon filled if not then unfilled. But I am facing an issue in that I create the logic for comparing them and then push in the state but it renders the product list first but does not show the icons filled. But if I make any changes in the component & save them crtl+s then show the icons filled. means it updates the state early. I did not find any solution to this.

import React, { useEffect, useState } from 'react';
import { product } from '../../../_services';
import "../../../_UI/slick-carousel/slick/slick.css";
import "../../../_UI/slick-carousel/slick/slick-theme.css";
import { Link } from 'react-router-dom';
import { useHistory } from 'react-router-dom'
import Slider from "react-slick";
import { useDispatch,useSelector} from 'react-redux';
import { CartActions,wishlistActions } from '../../../_actions';
function NewArrival() {
  const selector = useSelector((state)=>state);
  
  const dispatch = useDispatch();
  const [value, setvalue] = useState([]);
  
  const [value2, setvalue2] = useState([]);
  const settingSlider = {
    dots: true,
    slidesToShow: 4,
    slidesToScroll: 4,
    autoplay: true,
    autoplaySpeed: 5000,
    Speed:10,
    pauseOnHover:true,
    arrows: false,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 3,
          infinite: true,
        }
      },
      {
        breakpoint: 600,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 2,
          infinite: true,
        }
      },
      {
        breakpoint: 480,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1,
          infinite: true,
        }
      }
    ]

  }
  const AddToWishList = (sku_name)=>{
    dispatch(wishlistActions.AddToWishListRequested(sku_name))
  }
  const AddToCart = async (sku,index) => {
    const user_id = localStorage.getItem('card_id');
    let product_details = {
      sku_name: sku,
      qty: 1,
      quote_id: user_id
    }
    dispatch(CartActions.ADDCARTREQUEST(product_details,index));
  }
  useEffect(() => {
   newArrivalApi()
  }, [])
  
  async function newArrivalApi(){
    if(localStorage.getItem('user')){
    const result = await product.ProductsNewarrival(39);
    const result2 = await product.ProductsNewarrival(71)
    console.log(selector.WishListProcess.wishlist);
    //compare logic
    result2.data.items?.map((items,index)=>{
    selector?.WishListProcess?.wishlist?.map((item)=>{
         if(items.id==item.product_id){ 
             result2.data.items.push({...items,wishlist:true})
             result2.data.items.splice(index,1);  
            } 
    })
    })
    //compare logic second slider
     result.data.items?.map((items,index)=>{
        selector?.WishListProcess?.wishlist?.map((item)=>{ 
        if(items.id==item.product_id){
       result.data.items.push({...items,wishlist:true})
       result.data.items.splice(index,1);
        }
      })
    })




    // console.log(result.data.items);
    // console.log(result2.data.items);  
   
    setvalue(result?.data?.items); 
    setvalue2(result2?.data?.items)

   
  
  }
  else{
    const result = await product.ProductsNewarrival(39);
    const result2 = await product.ProductsNewarrival(71)
    console.log(result)
    console.log(result2);
    setvalue2(result2.data.items)
    setvalue(result.data.items)

  }
   }

  return (
    <>
    <section className="collection-section">
      {value?.length > 0 ?
        <div className="container-fluid">
          <div className="text-center my-5">
            <h3 className="heading-text">
              New Arrival
            </h3>
            <h4 className="sub-heading-text">
              "Fashion Fade. Style is eternal."
            </h4>
          </div>
       
          <div className="row align-items-lg-center">
            <div className="col-lg-9 col-md-9">
              <div className="row justify-content-lg-between justify-content-center" >
                <div className="col-lg-12">
                <Slider  {...settingSlider}>
                  {value.map((item, index) => {
                    return (
                    <div key={index} >
                      <div className="product-info">
                        <div className="product-image">
                          <Link to={"/product_details/" + item.sku} > <img src={item?.custom_attributes[0].attribute_code ==="image"  ? item.custom_attributes[0].value : item.custom_attributes[1].value }   alt='' className="img-fluid" /></Link>
                        </div>
                        <div className="product-title"><a href={"/product_details/" + item.sku}>{item.name}</a></div>
                        <div className="product-price">${item.price}</div>
                        <div className="add-wishlist-out">
                <div className="add-to-cart-outer">
                    <button onClick={()=>{AddToCart(item.sku,item.id)}} className="add-to-cart-btn"><i className="fa fa-solid fa-cart-shopping"></i>{selector?.CartProcess?.loading === true && selector?.CartProcess?.index === item.id ? "LOADING..." : "Add to cart"}</button>
                </div>
                <div className="wishlist-out">
                    <a onClick={()=>{AddToWishList(item.sku)}} className="wishlist-icon"><i className={item.wishlist===true ? "fa fa-solid fa-heart" :"far fa-heart"}></i></a>
                    <a href="#" className="compare-icon"><i className="fa fa-solid fa-signal"></i></a>
                </div>
              </div>
                      </div>
                    </div>
                  )})}
                </Slider>
                </div>
              </div>
            </div>
            <div className="col-lg-3 col-md-3">
              <div className="long-img">
                <img src="./assets/images/1608b80571524e822b386e9da05f02f2.jpg" className="img-fluid" />
              </div>
            </div>
          </div>
          <div className="row align-items-lg-center">
            <div className="col-lg-3 col-md-3">
              <div className="long-img">
                <img src="./assets/images/ww8.jpg" className="img-fluid" />
              </div>
            </div>
            <div className="col-lg-9 col-md-9">
              <div className="row justify-content-lg-between justify-content-center" >
                <div className="col-lg-12" >
                <Slider   {...settingSlider} >
                  {value2.map((item, index) => {
                    return (
                    <div key={index} >
                      <div className="product-info">
                        <div className="product-image">
                          <a href={'/product_details/' + item.sku} ><img src={item?.custom_attributes[0].attribute_code ==="image"  ? item.custom_attributes[0].value : item.custom_attributes[1].value } alt='' className="img-fluid" /></a>
                        </div>
                        <div className="product-title"><a href={"/product_details/" + item.sku}>{item.name}</a></div>
                        <div className="product-price">${item.price}</div>
                        <div className="add-wishlist-out">
                <div className="add-to-cart-outer">
                    <button onClick={()=>{AddToCart(item.sku,item.id)}} className="add-to-cart-btn"><i className="fa fa-solid fa-cart-shopping"></i>{selector?.CartProcess?.loading === true && selector?.CartProcess?.index === item.id ? "LOADING..." : "Add to cart"}</button>
                </div>
                <div className="wishlist-out">
                    <a onClick={()=>{AddToWishList(item.sku)}} className="wishlist-icon"><i className={item.wishlist===true ? "fa fa-solid fa-heart" :"far fa-heart"}></i></a>
                    <a href="#" className="compare-icon"><i className="fa fa-solid fa-signal"></i></a>
                </div>
              </div>
                      </div>
                    </div>
                  )})}
                </Slider>
                </div>
              </div>

            </div>
          </div>
        </div>
        : " "}
    </section>
    </>
  )
}


export { NewArrival };


Solution 1:[1]

That is the normal behavior of useState because useState is async function so it takes a little bit of time to set the state before use it so you have to find a way around to use it, I suggest why are you setting two set one state and inside its object like this:

const [valueState, setValueState] = React.useState({ result: [], result2: [] });
setValueState({ result: result?.data?.items, result2: result2?.data?.items });

and use it like this

valueState?.result
valueState?.result2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abbas Hussain