implemented custom useMarkers hook

main
Inga 🏳‍🌈 1 year ago
parent aa61cccda5
commit 2829b5f37d
  1. 9
      src/routePlanner/index.tsx
  2. 7
      src/routePlanner/useMarkers.test.ts
  3. 12
      src/routePlanner/useMarkers.ts

@ -1,17 +1,12 @@
import { useMemo, useReducer } from 'preact/hooks';
import { ExportComponent } from './export'; import { ExportComponent } from './export';
import { MapComponent } from './map'; import { MapComponent } from './map';
import { MarkersComponent } from './markers'; import { MarkersComponent } from './markers';
import { createChangeStateMethods, markersReducer } from './reducer'; import { useMarkers } from './useMarkers';
import './style.css'; import './style.css';
export const RoutePlanner = () => { export const RoutePlanner = () => {
const [markers, dispatchMarkers] = useReducer(markersReducer, []); const [markers, { reorderMarkers, addMarker }] = useMarkers();
const { reorderMarkers, addMarker } = useMemo(
() => createChangeStateMethods(dispatchMarkers),
[],
);
return ( return (
<section class="route-planner"> <section class="route-planner">

@ -1,6 +1,11 @@
import t from 'tap'; import t from 'tap';
import { Marker, ReducerAction } from './types'; import { Marker, ReducerAction } from './types';
import { createChangeStateMethods, markersReducer } from './reducer.js'; import { createChangeStateMethods, markersReducer } from './useMarkers.js';
// Testing entire `useMarkers` custom hook would require us to create test preact components here
// and render them into virtual DOM and check the results, which is just too much hassle
// (but that's how Facebook designed API of hooks, with all that stateful contextful magic hidden under the hood).
// So we'll only test `markersReducer` and `createChangeStateMethods` here.
const createReducerWithState = () => { const createReducerWithState = () => {
let markers: Marker[] = []; let markers: Marker[] = [];

@ -1,5 +1,5 @@
import { nanoid } from 'nanoid'; import { nanoid } from 'nanoid';
import { Dispatch } from 'preact/hooks'; import { Dispatch, useMemo, useReducer } from 'preact/hooks';
import { reorderElements } from '../shared/collections.js'; import { reorderElements } from '../shared/collections.js';
import { Coordinates } from '../shared/types'; import { Coordinates } from '../shared/types';
import { Marker, ReducerAction, ReorderMarkersParams } from './types'; import { Marker, ReducerAction, ReorderMarkersParams } from './types';
@ -129,3 +129,13 @@ export const createChangeStateMethods = (
addMarker, addMarker,
}; };
}; };
export const useMarkers = () => {
const [markers, dispatchMarkers] = useReducer(markersReducer, []);
const changeStateMethods = useMemo(
() => createChangeStateMethods(dispatchMarkers),
[],
);
return [markers, changeStateMethods] as const;
};
Loading…
Cancel
Save