Get latest value from redux store after fetching data

Viewed 16

I'm working on a component where we display a list of available home properties to the user. When the user clicks on a Property card, we make a call to an API that returns an array of objects with more info related to the property (we call these 'Warnings'), and we display them in a modal. The user has to confirm each of the Warnings by clicking on an Accept button inside the modal. Once there are no more Warnings to confirm, we navigate the user to the actual Property url, where they can see all its data. The issue i have is, once the user has confirmed all the Warnings, i am seeing the previous value of the warnings state variable in my function to move the user to the Property url. I believe this is happening because, after making the fetch request to get the Warnings, the Property component has not re-rendered yet and it's using the initial state value. This is the simplified code:

function Property ({ name, id, url, warnings, fetchWarnings }) {
  const [fetchedWarnings, setHasFetchedWarnings] = useState(false);
  const onFetchWarnings = () => {
    fetchWarnings(id);
    setHasFetchedWarnings(true);
  }

  useEffect(() => {
    if (hasFetchedWarnings && warnings.length === 0) {
       history.push(url);
    }
  }, [warnings])

  return (
    <div>
      <button onClick={() => onFetchWarnings() }>{ name } </button>
    </div>
  )
}

function msp (state) {
  return { warnings: PropertySelectors.getWarnings(state) }
}

function mdp (dispatch) {
  return bindActionCreators({ 
    getWarnings: PropertyActions.fetchWarnings             // this function fetches the data and updates the state.warnings in Redux
  }, dispatch)
}

export default Connect(msp, mdp)(Property)

How to properly fetch the data so that when I access the warnings array, it returns the latest data from the store and not the previous value?

0 Answers
Related