Now we are wanting to query that mock data in our application. We'll start off by installing npm i @apollo/client cross-fetch graphql
in our Next.js application.
We will create a new function called getStaticProps which will do all of our fetching using Apollo and GraphQL.
Instructor: [0:00] Next up, we want to query data from our Strapi application and render that in our Next.js application. [0:07] In our terminal, we stop our Strapi server and clear our screen. Now we'll install with npm i a couple of dependencies. First of all, @ApolloClient, cross-fetch, and GraphQL.
[0:31] Now that our dependencies are installed, we'll restart our server with yarn dev. In our frontend project folder, we'll create a new folder called config. Inside config, we'll create a new file called index.js.
[0:51] Inside index.js, we'll define a const dev and assign it the value process.env.node environment if not equal to production.
[1:12] Next, we exploit a const called server and use the ternary operator to check if our environment is the development one. If it is, we use http//localhost:1537. If it isn't, we use process.env.strapi URL and save.
[1:43] Next up, in pages/index.js, we want to import a couple of modules. We start out by importing fetch from cross-fetch. We also import server from our config folder, and we import Apollo Client client InMemoryCache with Capital I GQL and HTTP link, all from Apollo slash client, and save.
[2:50] At the bottom of our file, we'll initialize a getStaticProps function. Export missing function getStaticProps. This lets our Next.js application render pages at build time. With this, we'll initialize a new Apollo Client instance, and I'll paste in the configuration here.
[3:26] We'll create a new link object as well as a cache object that utilize HTTP link and in-memory cache. Next up, we visualize a const data, which will act as a store for our response. This will be equal to 08 client.query for GraphQL query and inside here we'll define our GraphQL query as query GQL.
[4:11] Then we can go into our Strapi GraphQL Playground and copy our query. To test out our query, before we can do that, we need to make sure we're getting an ID and then we can copy this query and paste it in VS code. We then need to return our props, which will be posts, and now will go into our data.
[4:55] At the top of our file where we export default our home function, and so now here we add posts to the home props. Just above our return, we console log posts. We save that and refresh our Next.js application. If we check our console, we should have our object data, object one, Humpty Dumpty, object two, Humpty Dumpty, with all our data. That is how you connect your Next.js application to your Strapi API.