I am trying to create a global state using a combination of useState with useContext in react using typescript.
#store.tsx
export const StoreContext = React.createContext();
export const StoreProvider = (({ children }: ChildrenType) => {
const [test] = React.useState(['world']);
const store = {
test,
};
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;
});
#app.tsx
import type { AppProps } from 'next/app'
import { StoreProvider } from '../store';
export default function App({ Component, pageProps }: AppProps) {
return (
<StoreProvider>
<Component {...pageProps} />
</StoreProvider>
)
}
#index.tsx
import React from 'react';
import { StoreContext } from '../store';
export default function Home() {
const { test: [test] } = React.useContext(StoreContext);
return (
<div>
<h1>
hello
{test}
</h1>
</div>
);
}
Now this works fine when I run in development mode (in this case npm run dev) however when I try and build it I get the following error:
$npm run build
> [email protected] build
> next build
info - Linting and checking validity of types .Failed to compile.
./pages/index.tsx:7:11
Type error: Property 'test' does not exist on type 'unknown'.
5 |
6 | export default function Home() {
> 7 | const { test: [test] } = React.useContext(StoreContext);
| ^
8 |
9 | return (
10 | <div0
I have created a POC that contains this example here: https://github.com/jamesla/state-poc
How can I make this work?