All files / client/src/app HistoryProvider.tsx

83.33% Statements 5/6
100% Branches 2/2
100% Functions 1/1
83.33% Lines 5/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31                520x 3281x 3281x                   3281x 1373x                  
import { ReactElement, ReactNode, useState } from "react";
import { Location, useLocation } from "react-router";
import { HistoryContext } from "client/app/historyContext";
 
interface Props {
  children: ReactNode;
}
 
export const HistoryProvider = ({ children }: Props): ReactElement => {
  const location = useLocation();
  const [visited, setVisited] = useState<{
    current: Location;
    previous: Location | null;
  }>({ current: location, previous: null });
 
  // Adjusted while rendering rather than in an effect, so a view mounting for
  // the new location already sees the one it came from. Keeping the location
  // the pair was derived from is what makes a re-render that doesn't navigate
  // leave the pair alone, instead of promoting the current location to being
  // its own predecessor
  if (visited.current !== location) {
    setVisited({ current: location, previous: visited.current });
  }
 
  return (
    <HistoryContext.Provider value={visited.previous}>
      {children}
    </HistoryContext.Provider>
  );
};