I have a simple custom hook called useFlightData
that has a couple of stateful objects created using useState
. Here is the code.
export const useFlightData = () => {
const [userFlightChoices, setUserFlightChoices] = useState<UserFlightChoices>(
{
departureDate: null,
fromAirport: null,
returnDate: null,
toAirport: null,
typeOfTrip: 'one-way',
}
);
const [outGoingFlights, setOutGoingFlights] = useState<Departures[]>([]);
const { setIsLoading } = useGlobalData();
useUpdateLogger(userFlightChoices, 'userFlightChoices');
return {
userFlightChoices,
outGoingFlights,
setUserFlightChoices,
};
};
When I try using the hook in another component as below. The state update does not reflect on the hook.
import React from 'react';
const AirportSearch = ({
config,
closeFunction,
}: {
config: AirportSearchConfig;
closeFunction: React.Dispatch<React.SetStateAction<boolean>>;
}) => {
const { outGoingFlights, setUserFlightChoices } = useFlightData();
const handleSettingUserChoicesObject = (airport: Airport) => {
setUserFlightChoices((prev) => {
const newUserFlightChoicesObject = {
...prev,
toAirport:
config.searching === 'destination-airport' ? airport : prev.toAirport,
fromAirport:
config.searching === 'origin-airport' ? airport : prev.fromAirport,
};
console.log(newUserFlightChoicesObject);
return newUserFlightChoicesObject;
});
};
return (
<div className="airports-list mt-8 search-results-airports h-28 overflow-y-scroll scroll">
{localAirportList.map((airport) => (
<div
key={airport.id}
className="flex justify-between cursor-pointer"
onClick={() => handleSettingUserChoicesObject(airport)}
>
<p className="font-bold text-sm ho">{airport.country}</p>
<p className="text-xs">{airport.name}</p>
</div>
))}
</div>
);
};
export default AirportSearch;
QUESTION:
When I log out the result of the setState callback in the function handleSettingUserChoicesObject
the object is created correctly. So I feel it's safe to assume it is also returned successfully. So why does the state update not reflect inside the hook? I have an updateLogger
function that logs out the variable each time it changes but somehow the updated object is not logged out. How can I make sure the state update is reflected throughout the app wherever I use my custom hook. Without using useContext?
this code is heavily decluttered