There will be cases when the data passed don’t actually change that often and because of that we would want to get this data from outside of the home item or somewhere from global location. This is where Next.js API Routes will come into the picture. Next.js has introduced a feature which allows creating API routes within Next.js without having to rely on backend integration.
I had the requirement to get the data from the global item in the Layout.tsx so I tried to create the GraphQLRequestClient but it is not allowed and gave me the error as:
graphql_request__WEBPACK_IMPORTED_MODULE_0__.GraphQLClient is not a constructor
So I got the link https://www.getfishtank.com/insights/utilizing-nextjs-api-routes-for-sitecore-xm-cloud-graphql-queries that helped me a lot. You can follow this for more detail but on high level I will mention how can we achieve to get the global data in the Layout.tsx file.
So below are the high level steps
- Create an API in next js app, as graphql query can access the data in the API
- Use that API's response in the Layout.tsx and do your logic what you want to achieve.
- Create an API in next js app, as graphql query can access the data in the API
In the path \src\sxastarter\src\pages\api\ create a file (this file name will be api endpoint) getglobalitemsetting.ts and paste the following code.
import { gql, GraphQLClient } from 'graphql-request';
import type { NextApiRequest, NextApiResponse } from 'next';
import config from 'temp/config';
const getGlobalItemSettingApi = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
const graphQLClient = new GraphQLClient(config.graphQLEndpoint);
graphQLClient.setHeader('sc_apikey', config.sitecoreApiKey);
console.log("method type: ", req.method)
if (req.method === 'GET') {
const query = gql`
query{
item(path: "/sitecore/content/MySiteSiteCollection/MySite/Settings" language:"en") {
field(name: "your field name") {
value
}
}
}
`;
const data = await graphQLClient.request(query);
return res.status(200).json(data);
} else {
return res.status(400).json({ message: 'Invalid method used.' });
}
};
export default getGlobalItemSettingApi;
This logic will return the response based on the graphql written in this method using http://localhost:3000/api/getglobalitemsetting.
2. Use that API's response in the Layout.tsx and do your logic what you want to achieve.
Write this code in the
const Layout = ({ layoutData }: LayoutProps): JSX.Element => {
const [isMyFieldChecked, setIsMyFIeldChecked] = useState<boolean | null>(null);
useEffect(() => {
const fetchChatSetting = async () => {
try {
const response = await fetch("/api/getglobalitemsetting");
if (!response.ok) {
throw new Error("Failed to fetch global item setting");
}
const data = await response.json();
// Extracting the value from the response
const isValue = data?.item?.field?.value === "1"; // Assuming 1 means enabled
setIsMyFIeldChecked(isValue);
} catch (error) {
console.error("Error fetching chat setting:", error);
}
};
fetchChatSetting();
}, []);
return (
<div>isMyFieldChecked</div>)
}
Thanks!