Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 142460

Accessing redux store using redux-hooks (useSelector)

$
0
0

In my component I am using useSelector hook to grab an array of objects from my store. Then I am parsing the results in a function. However, the issue is that when the component renders the function returns "-Infinity" and then it re-renders again to the correct value.

Below is console log of prices array map based on the hotelList.

Result of console.log(prices) inside getMaxPrice function

Here is my code:

const hotelList = useSelector(state => state.hotels)

  const getMaxPrice = () => {
    const prices = hotelList.map(
      ({ fields: { pricePerNight } }) => pricePerNight
    )
    console.log(prices)

    const max = Math.max(...prices)

    return max.toString()
  }

  const [state, setState] = useState({
    name: "",
    price: getMaxPrice(),
    stars: ""
  })

I think useSelector access store asynchronously therefore it is not available at first place. Is there a way to ensure that my hotelList is fully fetched from the store before continuing?


Viewing all articles
Browse latest Browse all 142460

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>