I’m working on a React project and have created a custom hook to fetch data from an API. I’ve set the state within this hook as follows after retrieving the data:
const [realEstates, setRealEstates] = useState<RealEstate[]>([]);
...
const fetchRealEstates = useCallback(async (request: GetRealEstatesByCustomerNumberRequest) : Promise<void> => {
try {
setError(null);
setLoading(true);
const response : GetRealEstatesByCustomerNumberResponse = await post('./api/Estate/get-real-estates-by-customer-number', request);
setRealEstates(response.RealEstates);
} catch (error: any) {
setError(error);
}
setLoading(false);
}, []);
...
I then use this custom hook in a component as shown below:
const { realEstates, fetchRealEstates } = useRealEstate();
...
const onCustomerSearchChangeValue = async (customer: any) => {
dispatch(setSelectedCustomerNumber(customer.value.ExternalClientNo));
await fetchRealEstates({ CustomerNumber: customer.value.ExternalClientNo });
dispatch(setRealEstates(realEstates));
};
...
My problem is that I seem to be missing something, potentially related to the nature of JavaScript itself. When the fetchRealEstates hook is executed, it successfully retrieves data from the API and updates the state within the hook through setRealEstates. However, I observe that the state within the hook is not being updated as expected, leading to the component not receiving the correct value.
Additionally, when this operation is executed in a new event, I receive the values that I was trying to access in the previous iteration. This suggests to me that I might be missing something related to the asynchronous nature of the operation or the component lifecycle.
I understand that this process is asynchronous, and I’m guessing that the hook needs to be re-rendered in some way to see the new state value (though I’m a bit unclear on this part).
I’m not sure what I’m missing here. Can anyone help?
2
Answers
I recently encountered a challenge in my React application involving state synchronization between a custom hook and a Redux store. After some experimentation and research, I discovered an effective solution that I'd like to share, along with an explanation of why it works and what I had initially overlooked.
I implemented a useEffect hook in the parent component that listens for changes in the realEstates data from my custom hook and then dispatches an action to update the Redux store.
I hope this will work for you too.
Happy coding.
According to your post you want to get data and yet you are making a post request Instead of a get request and your fiction fetchRealEstates returns void
Try this approach