Transform Firebase data with transform options
masterBoth useListVals and useObjectVal support a transform function in their options object. This allows you to convert raw Firebase data types (like strings or numbers) into application-specific types (like Date objects).
Usage Notes:
- The
transformfunction signature is(val: any) => T. - It is called once for
useObjectValand once per item foruseListVals. - The
transformfunction does not receivekeyorrefvalues; if you usekeyFieldorrefField, those properties are merged into the result after transformation. - Performance: If defining the
transformfunction inside a React component, memoize it (e.g., usinguseCallback) to prevent unnecessary re-renders.
Example: Converting a string to a Date object
type SaleType = {
idSale: string,
date: Date,
};
const options = {
keyField: 'idSale',
transform: (val) => ({
...val,
date: new Date(val.date),
}),
};
// Usage in a custom hook
export const useSale = (idSale: string) =>
useObjectVal<SaleType>(database.ref(`sales/${idSale}`), options);type SaleType = {
idSale: string,
date: Date, // <== it is declared as type Date which Firebase does not support.
// ...Other fields
};
const options = {
keyField: 'idSale',
transform: (val) => ({
...val,
date: new Date(val.date),
}),
};
export const useSale: (
idSale: string
) => [SaleType | undefined, boolean, any] = (idSale) =>
useObjectVal < SaleType > (database.ref(`sales/${idSale}`), options);
export const useSales: () => [SaleType[] | undefined, boolean, any] = () =>
useListVals < SaleType > (database.ref('sales'), options);