I am unable to access account
or any other property from DataContextProps
.
context/Datacontext.tsx
interface DataContextProps {
account: string;
contract: any;
loading: any;
images: any[];
imageCount: number;
updateImages: () => Promise<void>;
donateImageOwner: (id: string, DonateAmount: any) => Promise<void>;
};
const DataContext = createContext<DataContextProps | null>(null);
interface Props {
children?: React.ReactNode;
};
export const DataProvider: React.FC<Props> = ({ children }) => {
const data = useProviderData();
return <DataContext.Provider value={data}>{children}</DataContext.Provider>;
};
export const useData = () => useContext<DataContextProps | null>(DataContext);
Header.tsx
import Identicon from "identicon";
import React, { useEffect } from "react";
import { useData } from "../../contexts/DataContext";
function Header() {
const { account } = useData();
const [data, setData] = React.useState();
useEffect(() => {
if (account !== "0x0") {
setData(new Identicon(account, 200).toString());
}
}, [account]);
return ()
}
export default Header;
it's because property account
does not exist in type null
, you can define an initialDataContextProps
object with properties in their initial state, and remove union null
from createContext
generics, take this for example:
const initialDataContextProps = {
account: "";
contract: null;
loading: null;
images: [];
imageCount: 0;
updateImages: async () => {};
donateImageOwner: async (id: string, DonateAmount: any) => {};
};
const DataContext = createContext<DataContextProps>(initialDataContextProps)
/* ...other code */
export const useData = () => useContext(DataContext); // no generics needed