Let me share the issue I am facing. I have developed a custom Context API wrapper to handle all my data. However, there is this docType
property that may not always be defined or may not exist at times.
When I destructure it in this way:
const { docType } children?.props?.data; // My Next App / JS crashes and getting the undefined error.
This approach seems to work fine:
const docType = children.props.data?.docType;
I'm wondering why this discrepancy exists. If I don't follow this specific structuring for my code, other data props fail to destructure properly. Here's how I've set up my context with React:
import { createContext, useContext } from "react";
const AppContext = createContext();
export const AppWrapper = ({ children }) => {
const docType = children.props.data?.docType;
const site = children.props.data?.site;
const page = children.props.data?.page;
const preview = children.props?.preview;
const sharedState = {
docType,
preview,
page,
site,
};
return (
<AppContext.Provider value={sharedState}>{children}</AppContext.Provider>
);
};
export const useAppContext = () => useContext(AppContext);
If anyone could shed some light on why I encounter this issue, it would be greatly appreciated.