Rvfvl
Rvfvl

Reputation: 383

Accessing redux store using redux-hooks (useSelector)

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?

Upvotes: 1

Views: 1434

Answers (1)

tony
tony

Reputation: 1326

The very first time the array is empty and Math.max(...[]) returns -Infinity. In some cases using ... spread operator will fail as suggested on MDN . The safe way to do what you want is

var max = prices.reduce(function(a, b) {
    return Math.max(a, b);
});

Upvotes: 1

Related Questions