I’m hitting an API to return some data that I’m passing into a useState hook so I can map over that data and display to the user but for some reason the data does not update without a manual refresh. FYI I’m using Redux saga and Redux selectors to retrieve the data from state but that is besides the point. Here is snippets of the relevant code below:
import React, {useState} from 'react'
const BillingAddressDetails = () => {
const activeAddresses = useAppSelector(getProfileActiveAddresses);
const [sortedActiveAddresses, setSortedActiveAddresses] = useState([...activeAddresses]};
return (
sortedActiveAddresses.map(address => <BillingAddressCard={address} />
};
const BillingAddressCard = ({address}) => {
return (
<div>
<span>{address.firstName} {address.lastName}</span>
<span>{address.streetLine1}</span>
<span>{address.city}</span>
</div>
)
}
I have a button that hits a PUT API to update a single address but after a successful API response, when I console.log activeAddresses I see the correct data and the correctly updated address, but if I console.log sortedActiveAddresses, I see the old data and the address that was updated is not updated. If I manually refresh the page then I get the correct data with the updated address. Also if I remove the useState completely and just map over the activeAddresses to give the BillingAddressCard components data to display, I get the same thing where I need to manually refresh to display the correct data. What am I missing here? Thank you for the help!
franklin1551 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.