Best way to create utility functions for use in async and sync components. #1357
-
I'm currently in the process of added I was able to create a hook function that encloses export function useFormatDistance() {
const t = useTranslations("unit_formats");
return ({ distance, unitSystem, useAbbreviation }: FormatOptions) => {
// ... formatting logic
};
} This solution works perfectly, however it cannot be used within async components as I'm using Is the solution to have two functions, one for async components and one for not, which then called a shared function formatDistance ({ distance, unitSystem, useAbbreviation, translations }: FormatOptionsWithTranslations) {
// ... formatting logic
}
export function useFormatDistance() {
const t = useTranslations("unit_formats");
return ({ distance, unitSystem, useAbbreviation }: FormatOptions) => {
const translations = { ... } // include all translations that the `formatDistance()` may require.
formatDistance({distance, unitSystem, useAbbreviation, translations});
};
}
export async function getFormatDistance() {
const t = await getTranslations("unit_formats");
return ({ distance, unitSystem, useAbbreviation }: FormatOptions) => {
const translations = { ... } // include all translations that the `formatDistance()` may require.
formatDistance({distance, unitSystem, useAbbreviation, translations});
};
} The downside of this is composing the Any input would be greatly appreciated 😊 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
This is a good question, yes! The fact that hooks can currently not be called in Would it really help though to pass a Depending on your use case, maybe a component like |
Beta Was this translation helpful? Give feedback.
Yep, that's true. The
t
function needs to be unscoped in this case though, containing all possible translations. That in turn could make the usage oft
harder in the calling component, if it also has to render translations. This sounds like an indicator to me thatt
should really be retrieved as part of your format distance utility (whether it's an async function, hook or component).Personally, I like to use async components rather sparingly for data fetching and typically leave all rendering behavior to non-async components. This has the nice side effect that aspects like testing, isolated rendering in Storybook etc., work without tradeoffs. In this case it'd also help to offer a single
u…