Next 13 + React 18 build problem with createContext type

153 Views Asked by At

I'm trying to build a project, but the type check gives this error:

Type error: Type 'OmitWithTag<typeof import("....calculator/page"), "metadata" | "default" | "config" | "generateStaticParams" | "revalidate" | ... 6 more ... | "generateMetadata", "">' does not satisfy the constraint '{ [x: string]: never; }'. Property 'ActiveTabContext' is incompatible with index signature. Type 'Context<ActiveTab>' is not assignable to type 'never'.

createContext code:

type ActiveTab = [string, Dispatch<SetStateAction<string>>]
type SelectValues = [IApiCostsState[], Dispatch<SetStateAction<IApiCostsState[]>>]
type SumState = [number, Dispatch<SetStateAction<number>>]
type HelperState = [Helper, Dispatch<SetStateAction<Helper>>]

export const ActiveTabContext = createContext<ActiveTab>(['', () => { }]) as Context<ActiveTab>;
export const SelectValuesContext = createContext<SelectValues>([setInitial(Object.keys(_apiCostsMock)[0]), () => { }]);
export const TotalSumContext = createContext<SumState>([0, () => { }]);
export const HelperContext = createContext<HelperState>([{index:-1}, () => { }]);
export const WindowWidthContext = createContext<number>(0);
export const ScrollElementContext = createContext<MutableRefObject<HTMLDivElement | null> | null>(null);

Transferring contexts to layout.tsx gives the same error. This problem is for all contexts in the file.

What's wrong with context typing? And how i can fix that?

1

There are 1 best solutions below

0
Hamude Shahin On BEST ANSWER

try creating context like this

import { createContext } from "react";

interface ModalContextProps {
  show: (content: ReactNode) => void;
  hide: () => void;
}

const ModalContext = createContext<ModalContextProps | undefined>(undefined);

export function ModalProvider({ children }: { children: ReactNode }) {
  const [modalContent, setModalContent] = useState<ReactNode | null>(null);
  const [showModal, setShowModal] = useState(false);

  const show = (content: ReactNode) => {
    setModalContent(content);
    setShowModal(true);
  };

  const hide = () => {
    setShowModal(false);
    setTimeout(() => {
      setModalContent(null);
    }, 300); // Adjust this timeout as per your transition duration
  };

  return (
    <ModalContext.Provider value={{ show, hide }}>
      {children}
      {showModal && (
        <Modal showModal={showModal} setShowModal={setShowModal}>
          {modalContent}
        </Modal>
      )}
    </ModalContext.Provider>
  );
}

export function useModal() {
  return useContext(ModalContext);
}