AppState.tsx 787 Bytes
Newer Older
mayi's avatar
mayi committed
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
import * as React from "react";
import { useState } from "react";

interface AppState {
  username: string;
  shoppingCart: { items: { id: number; name: string }[] };
}
const defaultContextValue: AppState = {
  username: "徐嘉其",
  shoppingCart: { items: [] },
};
export const appSetStateContext =
  React.createContext<
    React.Dispatch<React.SetStateAction<AppState>> | undefined
  >(undefined);
export const appContext = React.createContext(defaultContextValue);
export const AppStateProvider: React.FC = (props) => {
  const [state, setState] = useState(defaultContextValue);
  return (
    <appContext.Provider value={state}>
      <appSetStateContext.Provider value={setState}>
        {props.children}
      </appSetStateContext.Provider>
    </appContext.Provider>
  );
};