@@ -15,10 +15,12 @@ import { useMemo } from "react";
1515export const useSqlPlot = <
1616 RowShape extends UnknownObjectShape ,
1717 SqlParams extends object ,
18- MappedRow extends UnknownObjectShape
18+ MappedRow extends UnknownObjectShape ,
19+ ReducedRow extends UnknownObjectShape
1920> ( {
2021 sqlParams,
2122 mapRows,
23+ reduceRows,
2224 buildQuery,
2325 makePlotOptions,
2426 isRenderable,
@@ -34,6 +36,11 @@ export const useSqlPlot = <
3436 * to a `Date` object.
3537 */
3638 mapRows ?: ( row : RowShape ) => MappedRow ;
39+
40+ /**
41+ * An optional function to transform the mapped rows into a different aggregation
42+ */
43+ reduceRows ?: ( rows : MappedRow [ ] ) => ReducedRow [ ] ;
3744 /**
3845 * A builder function that returns a SQL query given a set of parameters, which
3946 * will be the parameters passed as the `sqlParams` parameter.
@@ -43,7 +50,7 @@ export const useSqlPlot = <
4350 * A function to call after receiving the result of the SQL query (and mapping
4451 * its rows if applicable), to create the options given to Observable {@link Plot.plot}
4552 */
46- makePlotOptions : ( rows : MappedRow [ ] ) => Plot . PlotOptions ;
53+ makePlotOptions : ( rows : ReducedRow [ ] ) => Plot . PlotOptions ;
4754 /**
4855 * A function to call to determine if the chart is renderable. This is helpful
4956 * during server side rendering, when Observable Plot doesn't typically work well,
@@ -73,10 +80,27 @@ export const useSqlPlot = <
7380 ) ;
7481 } , [ response , error ] ) ;
7582
76- const plotOptions = useMemo ( ( ) => makePlotOptions ( mappedRows ) , [ mappedRows ] ) ;
83+ const reducedRows = useMemo ( ( ) => {
84+ if ( mappedRows . length === 0 ) {
85+ return [ ] ;
86+ }
87+
88+ if ( ! reduceRows ) {
89+ return mappedRows as unknown as ReducedRow [ ] ;
90+ }
91+
92+ return reduceRows ( mappedRows ) ;
93+ } , [ mappedRows ] ) ;
94+
95+ console . log ( JSON . stringify ( reducedRows ) ) ;
96+
97+ const plotOptions = useMemo (
98+ ( ) => makePlotOptions ( reducedRows ) ,
99+ [ reducedRows ]
100+ ) ;
77101
78102 useEffect ( ( ) => {
79- if ( mappedRows === undefined ) {
103+ if ( reducedRows === undefined ) {
80104 return ;
81105 }
82106
@@ -90,7 +114,7 @@ export const useSqlPlot = <
90114 }
91115
92116 return ( ) => plot . remove ( ) ;
93- } , [ mappedRows ] ) ;
117+ } , [ reducedRows ] ) ;
94118
95119 const renderPlot = useCallback (
96120 ( ) => < div ref = { containerRef } /> ,
0 commit comments