How to Fetch GraphQL Data in Next.js with Apollo GraphQL

Learn how to request GraphQL data in Next.js with Apollo Client. We’ll walk through:

  • Creating a new Next.js app
  • Installing Apollo Client and GraphQL
  • Using getStaticProps to fetch GraphQL data from the SpaceX API
  • Use launch data to create an app

Next.js has been steadily growing as a must-have tool for developers creating React apps. Part of what makes it great is its data fetching APIs that request data for each page. But how can we use that API to make GraphQL queries for our app?

  • What is GraphQL?
  • What is Apollo GraphQL?
  • Fetching data in Next.js
  • What are we going to build?
  • Step 0: Creating a new Next.js app
  • Step 1: Adding Apollo GraphQL to a Next.js app
  • Step 2: Adding data to a Next.js page with getStaticProps
  • Step 3: Fetch data with a GraphQL query in Next.js using Apollo Client
  • Step 4: Adding SpaceX launch data to the page

What is GraphQL?

GraphQL is a query language and runtime that provides a different way of interacting with an API than what you would expect with a traditional REST API.

When fetching data, instead of making a GET request to a URL to grab that data, GraphQL endpoints take a “query”. That query consists of what data you want to grab, whether it’s an entire dataset or a limited portion of it.

If your data looks something like this:

Movie {
  "title": "Sunshine",
  "releaseYear": "2007",
  "actors": [...],
  "writers": [...]
}

And you only want to grab the title and the year it was released, you could send in a query like this:

Movie {
  title
  releaseYear
} 

Grabbing only the data you need.

The cool thing is, you can also provide complex relationships between the data. With a single query, you could additionally request that data from different parts of the database that would traditionally take multiple requests with a REST API.

What is Apollo GraphQL?

Apollo GraphQL at its core is a GraphQL implementation that helps people bring together their data as a graph.

Apollo also provides and maintains a GraphQL client, which is what we’re going to use, that allows people to programmatically interact with a GraphQL API.

Using Apollo’s GraphQL client, we’ll be able to make requests to a GraphQL API similar to what we would expect with a REST-based request client.

Fetching data in Next.js

When fetching data with Next.js, you have a few options for how you want to fetch that data.

First, you could go the client side route and make the request once the page loads. The issue with this is that you’re then putting the burden on the client to take the time to make those requests.

The Next.js APIs like getStaticProps and getServerSideProps allow you to collect data at different parts of the lifecycle, giving us the opportunity to make a completely static app or one that’s server-side rendered. That will serve the data already rendered to the page straight to the browser.

By using one of those methods, we can request data along with our pages and inject that data as props right into our app.

What are we going to build?

We’re going to create a Next.js app that shows the latest launches from SpaceX.

SpaceX launches demo

We’ll use the API maintained by SpaceX Land to make a GraphQL query that grabs the last 10 flights. Using getStaticProps, we’ll make that request at build time, meaning our page will be rendered statically with our data.

Step 0: Creating a new Next.js app

Using Create Next App, we can quickly spin up a new Next.js app that we can use to immediately start diving into the code.

Inside your terminal, run the command:

npx create-next-app my-spacex-launches

Note: you don’t have to use _my-spacex-app_, feel free to replace that with whatever name you want to give the project.

After running that script, Next.js will set up a new project and install the dependencies.

Once finished, you can start up your development server:

cd my-spacex-launches
npm run dev

This will start a new server at http://localhost:3000 where you can now visit your new app!

New Next.js app

Step 1: Adding Apollo GraphQL to a Next.js app

To get started with making a GraphQL query, we’ll need a GraphQL client. We’ll use the Apollo GraphQL Client to make our queries to the SpaceX GraphQL server.

Back inside of the terminal, run the following command to install our new dependencies:

npm install @apollo/client graphql

This will add the Apollo Client as well as GraphQL, which we’ll need to to form the GraphQL query.

And once installation completes, we’ll be ready to get started Using Apollo Client.

Follow along with the commit!

Step 2: Adding data to a Next.js page with getStaticProps

Before we fetch any data with Apollo, we’re going to set up our page to be able to request data then pass that data as a prop to our page at build time.

Let’s define a new function at the bottom of the page below our Home component called getStaticProps:

export async function getStaticProps() {
  // Code will go here
}

When Next.js builds our app, it knows to look for this function. So when we export it, we’re letting Next.js know we want to run code in that function.

Inside our getStaticProps function, we’re going to be ultimately returning our props to the page. To test this out, let’s add the following to our function:

export async function getStaticProps() {
  return {
    props: {
      launches: []
    }
  }
}

Here, we’re passing a new prop of launches and setting it to an empty array.

Now, back inside of our Home component, let’s add a new destructured argument that will serve as our prop along with a console.log statement to test our new prop:

export default function Home({ launches }) {
  console.log('launches', launches);

If we reload the page, we can see that we’re now logging out our new prop launches which includes an empty array just like we defined.

Logging launches prop

The great thing about this is that given that the getStaticProps function we’re creating is asynchronous, we can make any request we’d like (including a GraphQL query) and return it as props to our page, which is what we’ll do next.

Follow along with the commit!

Step 3: Fetch data with a GraphQL query in Next.js using Apollo Client

Now that our application is prepared to add props to the page and we have Apollo installed, we can finally make a request to grab our SpaceX data.

Here, we’re going to use the Apollo Client, which will allow us to interface with the SpaceX GraphQL server. We’ll make our request to the API using the Next.js getStaticProps method, allowing us to dynamically create props for our page when it builds.

First, let’s import our Apollo dependencies into the project. At the top of the page add:

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

This is going to include the Apollo Client itself, InMemoryCache which allows Apollo to optimize by reading from cache, and gql which we’ll use to form our GraphQL query.

Next, to use the Apollo Client, we need to set up a new instance of it.

Inside the top of the getStaticProps function, add:

const client = new ApolloClient({
  uri: 'https://api.spacex.land/graphql/',
  cache: new InMemoryCache()
});

This creates a new Apollo Client instance using the SpaceX API endpoint that we’ll use to query against.

With our client, we can finally make a query. Add the following code below the client:

const { data } = await client.query({
  query: gql`
    query GetLaunches {
      launchesPast(limit: 10) {
        id
        mission_name
        launch_date_local
        launch_site {
          site_name_long
        }
        links {
          article_link
          video_link
          mission_patch
        }
        rocket {
          rocket_name
        }
      }
    }
  `
});

This does a few things:

  • Creates a new GraphQL query inside of the gql tag
  • Creates a new query request using client.query
  • It uses await to make sure it finishes the request before continuing
  • And finally destructures data from the results, which is where the information we need is stored

Inside of the GraphQL query, we’re telling the SpaceX API that we want to get launchesPast, which are the previous launches from SpaceX, and we want to get the last 10 of them (limit). Inside that, we define the data we’d like to query.

If we take a second to add a new console log statement after that, we can see what data looks like.

Once you refresh the page though, you’ll notice that you’re not seeing anything inside of the browser’s console.

getStaticProps runs during the build process, meaning, it runs in node. Because of that, we can look inside of our terminal and we can see our logs there:

Logging data to the terminal

After seeing that, we know that inside of the data object, we have a property called launchesPast, which includes an array of launch details.

Now, we can update our return statement to use launchesPast:

return {
  props: {
    launches: data.launchesPast
  }
}

And if we add our console.log statement back to the top of the page to see what our launches prop looks like, we can see our launch data is now available as a prop to our page:

Logging props to web console

Follow along with the commit!

Step 4: Adding SpaceX launch data to the page

Now for the exciting part!

We have our launch data that we were able to use Apollo Client to request from the SpaceX GraphQL server. We made that request in getStaticProps so that we could make our data available as the launches prop that contains our launch data.

Digging into the page, we’re going to take advantage of what already exists. For instance, we can start by updating the h1 tag and the paragraph below it to something that describes our page a little bit better.

Updated page title

Next, we can use the already existing link cards to include all of our launch information.

To do this, let’s first add a map statement inside of the page’s grid, where the component we return is one of the cards, with launch details filled in:

<div className={styles.grid}>
  {launches.map(launch => {
    return (
      <a key={launch.id} href={launch.links.video_link} className={styles.card}>
        <h3>{ launch.mission_name }</h3>
        <p><strong>Launch Date:</strong> { new Date(launch.launch_date_local).toLocaleDateString("en-US") }</p>
      </a>
    );
  })}

We can also get rid of the rest of the default Next.js cards including Documentation and Learn.

Page with SpaceX launches

Our page now includes the last 10 launches from SpaceX along with the date of the launch!

We can even click any of those cards, and because we linked to the video link, we can now see the launch video.

Follow along with the commit!

🗒️ Original Post
https://www.freecodecamp.org/news/how-to-fetch-graphql-data-in-next-js-with-apollo-graphql/

#apollo #graphql #next #database #developer

What is GEEK

Buddha Community

How to Fetch GraphQL Data in Next.js with Apollo GraphQL
 iOS App Dev

iOS App Dev

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

NBB: Ad-hoc CLJS Scripting on Node.js

Nbb

Not babashka. Node.js babashka!?

Ad-hoc CLJS scripting on Node.js.

Status

Experimental. Please report issues here.

Goals and features

Nbb's main goal is to make it easy to get started with ad hoc CLJS scripting on Node.js.

Additional goals and features are:

  • Fast startup without relying on a custom version of Node.js.
  • Small artifact (current size is around 1.2MB).
  • First class macros.
  • Support building small TUI apps using Reagent.
  • Complement babashka with libraries from the Node.js ecosystem.

Requirements

Nbb requires Node.js v12 or newer.

How does this tool work?

CLJS code is evaluated through SCI, the same interpreter that powers babashka. Because SCI works with advanced compilation, the bundle size, especially when combined with other dependencies, is smaller than what you get with self-hosted CLJS. That makes startup faster. The trade-off is that execution is less performant and that only a subset of CLJS is available (e.g. no deftype, yet).

Usage

Install nbb from NPM:

$ npm install nbb -g

Omit -g for a local install.

Try out an expression:

$ nbb -e '(+ 1 2 3)'
6

And then install some other NPM libraries to use in the script. E.g.:

$ npm install csv-parse shelljs zx

Create a script which uses the NPM libraries:

(ns script
  (:require ["csv-parse/lib/sync$default" :as csv-parse]
            ["fs" :as fs]
            ["path" :as path]
            ["shelljs$default" :as sh]
            ["term-size$default" :as term-size]
            ["zx$default" :as zx]
            ["zx$fs" :as zxfs]
            [nbb.core :refer [*file*]]))

(prn (path/resolve "."))

(prn (term-size))

(println (count (str (fs/readFileSync *file*))))

(prn (sh/ls "."))

(prn (csv-parse "foo,bar"))

(prn (zxfs/existsSync *file*))

(zx/$ #js ["ls"])

Call the script:

$ nbb script.cljs
"/private/tmp/test-script"
#js {:columns 216, :rows 47}
510
#js ["node_modules" "package-lock.json" "package.json" "script.cljs"]
#js [#js ["foo" "bar"]]
true
$ ls
node_modules
package-lock.json
package.json
script.cljs

Macros

Nbb has first class support for macros: you can define them right inside your .cljs file, like you are used to from JVM Clojure. Consider the plet macro to make working with promises more palatable:

(defmacro plet
  [bindings & body]
  (let [binding-pairs (reverse (partition 2 bindings))
        body (cons 'do body)]
    (reduce (fn [body [sym expr]]
              (let [expr (list '.resolve 'js/Promise expr)]
                (list '.then expr (list 'clojure.core/fn (vector sym)
                                        body))))
            body
            binding-pairs)))

Using this macro we can look async code more like sync code. Consider this puppeteer example:

(-> (.launch puppeteer)
      (.then (fn [browser]
               (-> (.newPage browser)
                   (.then (fn [page]
                            (-> (.goto page "https://clojure.org")
                                (.then #(.screenshot page #js{:path "screenshot.png"}))
                                (.catch #(js/console.log %))
                                (.then #(.close browser)))))))))

Using plet this becomes:

(plet [browser (.launch puppeteer)
       page (.newPage browser)
       _ (.goto page "https://clojure.org")
       _ (-> (.screenshot page #js{:path "screenshot.png"})
             (.catch #(js/console.log %)))]
      (.close browser))

See the puppeteer example for the full code.

Since v0.0.36, nbb includes promesa which is a library to deal with promises. The above plet macro is similar to promesa.core/let.

Startup time

$ time nbb -e '(+ 1 2 3)'
6
nbb -e '(+ 1 2 3)'   0.17s  user 0.02s system 109% cpu 0.168 total

The baseline startup time for a script is about 170ms seconds on my laptop. When invoked via npx this adds another 300ms or so, so for faster startup, either use a globally installed nbb or use $(npm bin)/nbb script.cljs to bypass npx.

Dependencies

NPM dependencies

Nbb does not depend on any NPM dependencies. All NPM libraries loaded by a script are resolved relative to that script. When using the Reagent module, React is resolved in the same way as any other NPM library.

Classpath

To load .cljs files from local paths or dependencies, you can use the --classpath argument. The current dir is added to the classpath automatically. So if there is a file foo/bar.cljs relative to your current dir, then you can load it via (:require [foo.bar :as fb]). Note that nbb uses the same naming conventions for namespaces and directories as other Clojure tools: foo-bar in the namespace name becomes foo_bar in the directory name.

To load dependencies from the Clojure ecosystem, you can use the Clojure CLI or babashka to download them and produce a classpath:

$ classpath="$(clojure -A:nbb -Spath -Sdeps '{:aliases {:nbb {:replace-deps {com.github.seancorfield/honeysql {:git/tag "v2.0.0-rc5" :git/sha "01c3a55"}}}}}')"

and then feed it to the --classpath argument:

$ nbb --classpath "$classpath" -e "(require '[honey.sql :as sql]) (sql/format {:select :foo :from :bar :where [:= :baz 2]})"
["SELECT foo FROM bar WHERE baz = ?" 2]

Currently nbb only reads from directories, not jar files, so you are encouraged to use git libs. Support for .jar files will be added later.

Current file

The name of the file that is currently being executed is available via nbb.core/*file* or on the metadata of vars:

(ns foo
  (:require [nbb.core :refer [*file*]]))

(prn *file*) ;; "/private/tmp/foo.cljs"

(defn f [])
(prn (:file (meta #'f))) ;; "/private/tmp/foo.cljs"

Reagent

Nbb includes reagent.core which will be lazily loaded when required. You can use this together with ink to create a TUI application:

$ npm install ink

ink-demo.cljs:

(ns ink-demo
  (:require ["ink" :refer [render Text]]
            [reagent.core :as r]))

(defonce state (r/atom 0))

(doseq [n (range 1 11)]
  (js/setTimeout #(swap! state inc) (* n 500)))

(defn hello []
  [:> Text {:color "green"} "Hello, world! " @state])

(render (r/as-element [hello]))

Promesa

Working with callbacks and promises can become tedious. Since nbb v0.0.36 the promesa.core namespace is included with the let and do! macros. An example:

(ns prom
  (:require [promesa.core :as p]))

(defn sleep [ms]
  (js/Promise.
   (fn [resolve _]
     (js/setTimeout resolve ms))))

(defn do-stuff
  []
  (p/do!
   (println "Doing stuff which takes a while")
   (sleep 1000)
   1))

(p/let [a (do-stuff)
        b (inc a)
        c (do-stuff)
        d (+ b c)]
  (prn d))
$ nbb prom.cljs
Doing stuff which takes a while
Doing stuff which takes a while
3

Also see API docs.

Js-interop

Since nbb v0.0.75 applied-science/js-interop is available:

(ns example
  (:require [applied-science.js-interop :as j]))

(def o (j/lit {:a 1 :b 2 :c {:d 1}}))

(prn (j/select-keys o [:a :b])) ;; #js {:a 1, :b 2}
(prn (j/get-in o [:c :d])) ;; 1

Most of this library is supported in nbb, except the following:

  • destructuring using :syms
  • property access using .-x notation. In nbb, you must use keywords.

See the example of what is currently supported.

Examples

See the examples directory for small examples.

Also check out these projects built with nbb:

API

See API documentation.

Migrating to shadow-cljs

See this gist on how to convert an nbb script or project to shadow-cljs.

Build

Prequisites:

  • babashka >= 0.4.0
  • Clojure CLI >= 1.10.3.933
  • Node.js 16.5.0 (lower version may work, but this is the one I used to build)

To build:

  • Clone and cd into this repo
  • bb release

Run bb tasks for more project-related tasks.

Download Details:
Author: borkdude
Download Link: Download The Source Code
Official Website: https://github.com/borkdude/nbb 
License: EPL-1.0

#node #javascript

Gerhard  Brink

Gerhard Brink

1620629020

Getting Started With Data Lakes

Frameworks for Efficient Enterprise Analytics

The opportunities big data offers also come with very real challenges that many organizations are facing today. Often, it’s finding the most cost-effective, scalable way to store and process boundless volumes of data in multiple formats that come from a growing number of sources. Then organizations need the analytical capabilities and flexibility to turn this data into insights that can meet their specific business objectives.

This Refcard dives into how a data lake helps tackle these challenges at both ends — from its enhanced architecture that’s designed for efficient data ingestion, storage, and management to its advanced analytics functionality and performance flexibility. You’ll also explore key benefits and common use cases.

Introduction

As technology continues to evolve with new data sources, such as IoT sensors and social media churning out large volumes of data, there has never been a better time to discuss the possibilities and challenges of managing such data for varying analytical insights. In this Refcard, we dig deep into how data lakes solve the problem of storing and processing enormous amounts of data. While doing so, we also explore the benefits of data lakes, their use cases, and how they differ from data warehouses (DWHs).


This is a preview of the Getting Started With Data Lakes Refcard. To read the entire Refcard, please download the PDF from the link above.

#big data #data analytics #data analysis #business analytics #data warehouse #data storage #data lake #data lake architecture #data lake governance #data lake management

How to Fetch GraphQL Data in Next.js with Apollo GraphQL

Learn how to request GraphQL data in Next.js with Apollo Client. We’ll walk through:

  • Creating a new Next.js app
  • Installing Apollo Client and GraphQL
  • Using getStaticProps to fetch GraphQL data from the SpaceX API
  • Use launch data to create an app

Next.js has been steadily growing as a must-have tool for developers creating React apps. Part of what makes it great is its data fetching APIs that request data for each page. But how can we use that API to make GraphQL queries for our app?

  • What is GraphQL?
  • What is Apollo GraphQL?
  • Fetching data in Next.js
  • What are we going to build?
  • Step 0: Creating a new Next.js app
  • Step 1: Adding Apollo GraphQL to a Next.js app
  • Step 2: Adding data to a Next.js page with getStaticProps
  • Step 3: Fetch data with a GraphQL query in Next.js using Apollo Client
  • Step 4: Adding SpaceX launch data to the page

What is GraphQL?

GraphQL is a query language and runtime that provides a different way of interacting with an API than what you would expect with a traditional REST API.

When fetching data, instead of making a GET request to a URL to grab that data, GraphQL endpoints take a “query”. That query consists of what data you want to grab, whether it’s an entire dataset or a limited portion of it.

If your data looks something like this:

Movie {
  "title": "Sunshine",
  "releaseYear": "2007",
  "actors": [...],
  "writers": [...]
}

And you only want to grab the title and the year it was released, you could send in a query like this:

Movie {
  title
  releaseYear
} 

Grabbing only the data you need.

The cool thing is, you can also provide complex relationships between the data. With a single query, you could additionally request that data from different parts of the database that would traditionally take multiple requests with a REST API.

What is Apollo GraphQL?

Apollo GraphQL at its core is a GraphQL implementation that helps people bring together their data as a graph.

Apollo also provides and maintains a GraphQL client, which is what we’re going to use, that allows people to programmatically interact with a GraphQL API.

Using Apollo’s GraphQL client, we’ll be able to make requests to a GraphQL API similar to what we would expect with a REST-based request client.

Fetching data in Next.js

When fetching data with Next.js, you have a few options for how you want to fetch that data.

First, you could go the client side route and make the request once the page loads. The issue with this is that you’re then putting the burden on the client to take the time to make those requests.

The Next.js APIs like getStaticProps and getServerSideProps allow you to collect data at different parts of the lifecycle, giving us the opportunity to make a completely static app or one that’s server-side rendered. That will serve the data already rendered to the page straight to the browser.

By using one of those methods, we can request data along with our pages and inject that data as props right into our app.

What are we going to build?

We’re going to create a Next.js app that shows the latest launches from SpaceX.

SpaceX launches demo

We’ll use the API maintained by SpaceX Land to make a GraphQL query that grabs the last 10 flights. Using getStaticProps, we’ll make that request at build time, meaning our page will be rendered statically with our data.

Step 0: Creating a new Next.js app

Using Create Next App, we can quickly spin up a new Next.js app that we can use to immediately start diving into the code.

Inside your terminal, run the command:

npx create-next-app my-spacex-launches

Note: you don’t have to use _my-spacex-app_, feel free to replace that with whatever name you want to give the project.

After running that script, Next.js will set up a new project and install the dependencies.

Once finished, you can start up your development server:

cd my-spacex-launches
npm run dev

This will start a new server at http://localhost:3000 where you can now visit your new app!

New Next.js app

Step 1: Adding Apollo GraphQL to a Next.js app

To get started with making a GraphQL query, we’ll need a GraphQL client. We’ll use the Apollo GraphQL Client to make our queries to the SpaceX GraphQL server.

Back inside of the terminal, run the following command to install our new dependencies:

npm install @apollo/client graphql

This will add the Apollo Client as well as GraphQL, which we’ll need to to form the GraphQL query.

And once installation completes, we’ll be ready to get started Using Apollo Client.

Follow along with the commit!

Step 2: Adding data to a Next.js page with getStaticProps

Before we fetch any data with Apollo, we’re going to set up our page to be able to request data then pass that data as a prop to our page at build time.

Let’s define a new function at the bottom of the page below our Home component called getStaticProps:

export async function getStaticProps() {
  // Code will go here
}

When Next.js builds our app, it knows to look for this function. So when we export it, we’re letting Next.js know we want to run code in that function.

Inside our getStaticProps function, we’re going to be ultimately returning our props to the page. To test this out, let’s add the following to our function:

export async function getStaticProps() {
  return {
    props: {
      launches: []
    }
  }
}

Here, we’re passing a new prop of launches and setting it to an empty array.

Now, back inside of our Home component, let’s add a new destructured argument that will serve as our prop along with a console.log statement to test our new prop:

export default function Home({ launches }) {
  console.log('launches', launches);

If we reload the page, we can see that we’re now logging out our new prop launches which includes an empty array just like we defined.

Logging launches prop

The great thing about this is that given that the getStaticProps function we’re creating is asynchronous, we can make any request we’d like (including a GraphQL query) and return it as props to our page, which is what we’ll do next.

Follow along with the commit!

Step 3: Fetch data with a GraphQL query in Next.js using Apollo Client

Now that our application is prepared to add props to the page and we have Apollo installed, we can finally make a request to grab our SpaceX data.

Here, we’re going to use the Apollo Client, which will allow us to interface with the SpaceX GraphQL server. We’ll make our request to the API using the Next.js getStaticProps method, allowing us to dynamically create props for our page when it builds.

First, let’s import our Apollo dependencies into the project. At the top of the page add:

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

This is going to include the Apollo Client itself, InMemoryCache which allows Apollo to optimize by reading from cache, and gql which we’ll use to form our GraphQL query.

Next, to use the Apollo Client, we need to set up a new instance of it.

Inside the top of the getStaticProps function, add:

const client = new ApolloClient({
  uri: 'https://api.spacex.land/graphql/',
  cache: new InMemoryCache()
});

This creates a new Apollo Client instance using the SpaceX API endpoint that we’ll use to query against.

With our client, we can finally make a query. Add the following code below the client:

const { data } = await client.query({
  query: gql`
    query GetLaunches {
      launchesPast(limit: 10) {
        id
        mission_name
        launch_date_local
        launch_site {
          site_name_long
        }
        links {
          article_link
          video_link
          mission_patch
        }
        rocket {
          rocket_name
        }
      }
    }
  `
});

This does a few things:

  • Creates a new GraphQL query inside of the gql tag
  • Creates a new query request using client.query
  • It uses await to make sure it finishes the request before continuing
  • And finally destructures data from the results, which is where the information we need is stored

Inside of the GraphQL query, we’re telling the SpaceX API that we want to get launchesPast, which are the previous launches from SpaceX, and we want to get the last 10 of them (limit). Inside that, we define the data we’d like to query.

If we take a second to add a new console log statement after that, we can see what data looks like.

Once you refresh the page though, you’ll notice that you’re not seeing anything inside of the browser’s console.

getStaticProps runs during the build process, meaning, it runs in node. Because of that, we can look inside of our terminal and we can see our logs there:

Logging data to the terminal

After seeing that, we know that inside of the data object, we have a property called launchesPast, which includes an array of launch details.

Now, we can update our return statement to use launchesPast:

return {
  props: {
    launches: data.launchesPast
  }
}

And if we add our console.log statement back to the top of the page to see what our launches prop looks like, we can see our launch data is now available as a prop to our page:

Logging props to web console

Follow along with the commit!

Step 4: Adding SpaceX launch data to the page

Now for the exciting part!

We have our launch data that we were able to use Apollo Client to request from the SpaceX GraphQL server. We made that request in getStaticProps so that we could make our data available as the launches prop that contains our launch data.

Digging into the page, we’re going to take advantage of what already exists. For instance, we can start by updating the h1 tag and the paragraph below it to something that describes our page a little bit better.

Updated page title

Next, we can use the already existing link cards to include all of our launch information.

To do this, let’s first add a map statement inside of the page’s grid, where the component we return is one of the cards, with launch details filled in:

<div className={styles.grid}>
  {launches.map(launch => {
    return (
      <a key={launch.id} href={launch.links.video_link} className={styles.card}>
        <h3>{ launch.mission_name }</h3>
        <p><strong>Launch Date:</strong> { new Date(launch.launch_date_local).toLocaleDateString("en-US") }</p>
      </a>
    );
  })}

We can also get rid of the rest of the default Next.js cards including Documentation and Learn.

Page with SpaceX launches

Our page now includes the last 10 launches from SpaceX along with the date of the launch!

We can even click any of those cards, and because we linked to the video link, we can now see the launch video.

Follow along with the commit!

🗒️ Original Post
https://www.freecodecamp.org/news/how-to-fetch-graphql-data-in-next-js-with-apollo-graphql/

#apollo #graphql #next #database #developer

Cyrus  Kreiger

Cyrus Kreiger

1618039260

How Has COVID-19 Impacted Data Science?

The COVID-19 pandemic disrupted supply chains and brought economies around the world to a standstill. In turn, businesses need access to accurate, timely data more than ever before. As a result, the demand for data analytics is skyrocketing as businesses try to navigate an uncertain future. However, the sudden surge in demand comes with its own set of challenges.

Here is how the COVID-19 pandemic is affecting the data industry and how enterprises can prepare for the data challenges to come in 2021 and beyond.

#big data #data #data analysis #data security #data integration #etl #data warehouse #data breach #elt