During local development I get Error: Rendered more hooks than during the previous render.
in my app when refreshing.
I believe it’s because I am doing two calls in my provider. First to get an ID, and then using the ID to do another call.
How can I make my provider work if it has to wait for the first call?
export const VehicleProvider = ({
children,
}: PropsWithChildren<unknown>): JSX.Element => {
const { data: vehiclesData, loading: vehiclesLoading, refetch } = useQuery(VehicleDocument);
const { data: chargeSettingsData, loading: chargeSettingsLoading } = useQuery(GetChargeSettingsDocument, {
variables: {
input: { vehicleId: vehiclesData.id }, // <-- vehiclesData is undefined during first render
},
});
if (vehiclesLoading || chargeSettingsLoading) {
return <Loader size="FULLSCREEN" />;
}
return (
<VehicleProviderContext.Provider
value={{
vehicle,
chargeSettings,
}}
>
{children}
</VehicleProviderContext.Provider>
);
};
export const useVehicle = (): VehicleProviderContext => {
const context = useContext(VehicleProviderContext);
if (!context) {
throw new Error(`useVehicle must be used within a VehicleProvider`);
}
return context;
};
I stripped down my provider to make it easier to post here.
2
Answers
Thanks to @Arkellys I fixed it. I installed a linter and found out that this was not used in the right place. I moved somethings around and suddenly it worked, maybe it wasn't at the top of the component 🤷♂️
Used
vehiclesLoading
to check ifvehiclesData
has returned any data