I have the following React 18 code:
import { Dispatch, ReactNode, SetStateAction, Suspense, createContext, useEffect, useState } from "react";
import { InternalConfig } from "../types/config";
import config from "../src/config";
import React from "react";
export const EtechUIContext = createContext<[InternalConfig, Dispatch<SetStateAction<InternalConfig>>] | []>([]);
export default function EtechUIProvider({
children,
configPath,
options
}: {
children: ReactNode;
configPath: string;
options?: {
filter: string;
};
}) {
const [internalConfig, setInternalConfig] = useState<InternalConfig>({} as InternalConfig);
const [calledTimes, setCalledTimes] = useState(0);
useEffect(() => {
const init = async (configPath: string, options?: { filter: string }) => {
try {
const newConfig = await config().init(configPath, options);
setInternalConfig(newConfig);
setCalledTimes(0);
} catch (err: any) {
setCalledTimes((prev) => prev++);
if (calledTimes >= 3) {
throw new Error("Failed to initialize eTech UI. This is likely a bug, please report it :)");
}
}
};
if (Object.keys(internalConfig).length === 0) {
init(configPath, options);
}
}, [internalConfig, calledTimes]);
return (
<Suspense fallback={<p>Loading...</p>}>
<EtechUIContext.Provider value={[internalConfig, setInternalConfig]}>{children}.</EtechUIContext.Provider>
</Suspense>
);
}
This code calls an async init function and sets the internal config.
However, when I test code I get an error:
The above error occurred in the <TestConsumer> component:
at TestConsumer (/Users/ekrich/git/etech-ui/packages/etech-ui-utils/contexts/tests/EtechUI.spec.tsx:17:58)
at Suspense
at EtechUIProvider (/Users/ekrich/git/etech-ui/packages/etech-ui-utils/contexts/EtechUI.tsx:10:3)
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
Warning: Cannot update a component (`EtechUIProvider`) while rendering a different component (`TestConsumer`). To locate the bad setState() call inside `TestConsumer`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
at TestConsumer (/Users/ekrich/git/etech-ui/packages/etech-ui-utils/contexts/tests/EtechUI.spec.tsx:26:73)
at Suspense
at EtechUIProvider (/Users/ekrich/git/etech-ui/packages/etech-ui-utils/contexts/EtechUI.tsx:10:3)
The internal config is {}
(the default value). This is both in the provider and the consumer. I’ve tried following the error messages instructions in using suspense. Still no luck.