Reputation: 383
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.
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