Reading Sitecore GraphQL data in Next JS
Hello everyone, in this blog we will try to learn how we can fetch the data from Sitecore using GraphQL and build the component in Next JS application. We will utilize the Tiles component which was build in my last blog regarding GraphQL. The blog link is available Here
This is just an example as same component can be developed using Layout service also.
Lets see the code for the front end and try to see learn what each code function do.
import React from "react";
import {
GetStaticComponentProps,
useComponentProps,
JSS_MODE_DISCONNECTED,
GraphQLRequestClient,
} from '@sitecore-jss/sitecore-jss-nextjs';
import { StyleguideComponentProps } from 'lib/component-props';
import config from 'temp/config';
type ListItem = {
Image : {
src : string;
alt : string;
}
TileLink : {
target : string;
text : string;
url : string;
}
Title : {
value : string;
}
id : string;
}
const Tiles = (props: StyleguideComponentProps): JSX.Element => {
const data = props.rendering.uid
? useComponentProps<any>(props.rendering.uid)
: undefined;
console.log(data);
const{Datasource} = data;
const{targetItems} = Datasource.Tilelistitems;
return(
<>
{
data && Datasource && (
<div className="card-container">
<h3>{Datasource.field.TileHeader}</h3>
{
targetItems && targetItems.map((item : ListItem) => {
console.log(item.Title.value);
return (
<div className="card" key={item.id}>
<a href={item.TileLink.url} target={item.TileLink.target}>
<img src={item.Image.src} alt={item.Image.alt} />
<div className="card-content">
<h2 className="card-title">{item.Title.value}</h2>
</div>
</a>
</div>
)
})
}
</div>
)
}
</>
);
};
export default Tiles;
export const getStaticProps: GetStaticComponentProps = async (rendering, layoutData, context) => {
if (process.env.JSS_MODE === JSS_MODE_DISCONNECTED) {
return null;
}
const graphQLClient = new GraphQLRequestClient(config.graphQLEndpoint, {
apiKey: config.sitecoreApiKey,
});
let query = `query GetPageContent(
$contextItem: String!
$language: String!
$datasource: String!
) {
ParentItem: item(path: $contextItem, language: $language) {
id
field(name: "PageTitle") {
... on TextField {
value
}
}
}
Datasource: item(path: $datasource, language: $language) {
... on TileList {
id
field(name: "Tile Header") {
... on TextField {
TileHeader: value
}
}
Tilelistitems: field(name: "Tilelistitem") {
... on MultilistField {
targetItems {
... on Tiles {
id
Title : field(name: "Title") {
... on TextField {
value
}
}
Image : field (name:"Image"){
... on ImageField{
alt
src
}
}
TileLink : field(name:"TileLink"){
...on LinkField{
text
target
url
}
}
}
}
}
}
}
}
}`
const result = await graphQLClient.request<any>(query, {
datasource: rendering.dataSource,
contextItem: layoutData?.sitecore?.route?.itemId,
language: layoutData?.sitecore?.context?.language,
});
return result;
};
Let's see getStaticProps function. In Next.js, getStaticProps is a special asynchronous function that you can export from a page component. It is used for server-side rendering (SSR) and static site generation (SSG) to fetch data and pass it as props to your page component at build time. This allows you to pre-render pages with dynamic data, which can improve performance and SEO.
In our case, we are calling this function to call GraphQL endpoint. We pass the GraphQL query along with required parameters to get the data.
By default, when we are calling the getStaticProps function, it takes rendering, layoutData and current context as params. For better understanding see below code snippet. First we are building GraphQLRequestClient. This takes two parameter GraphQL endpoint and API key. Once client object is build we are calling the graphQLClient.request() method which is type of any in our case. We can defined a specfic type also if required. The request method takes GraphQL query and the parameters required for fetching data. Once we get the result, we can use it to build our required component.
/**
* Will be called during SSG
* @param {ComponentRendering} rendering
* @param {LayoutServiceData} layoutData
* @param {GetStaticPropsContext} context
*/
Now Let's understand our actual component code. First we are creating one Next JS Tiles component exactly similar to our component name in Sitecore. This component is taking props as parameter which is of type StyleguideComponentProps. Then we are using useComponentProps to get external data. In Sitecore Next JS we are using the approach suggested by Sitecore documents. This method takes rendering uid as parameter and its type is any in our case. Then we are storing the return result in data variable and use it for building the component html.
Once you build the front end stack, you will able to see the data in front end as shown below.
You can log the data to check the result return from the GraphQL api and verify the same in GraphQL Edge GUI also.
GraphQL UI response with same query
Hope you enjoyed this blog. Will be back with many more related to Headless as my learning will continue.
You can check my other blogs blog related to SitecoreThanks for reading. Happy Learning!!
Comments
Post a Comment