Next.js Server Side React Fetch JSONPlaceholder API Example Using isomorphic-unfetch Library Full Project For Beginners

Next.js Server Side React Fetch JSONPlaceholder API Example Using isomorphic-unfetch Library Full Project For Beginners

 

 

 

Welcome folks today in this example we will be building a next.js application where we will be using the library isomorphic-unfetch library to make api calls. All the source code of the example will be shown below.

 

 

 

What is Next.js?

 

 

 

Before moving on, if you don’t know about next.js. It is a modern react.js framework for building server side applications using react. As you know react,angular and vue are frontend frameworks. So next.js allows us to write server side react applications.

 

 

 

 

Get Started

 

 

 

Now we know next.js. In order to get started with the project we need to create a new directory and inside that directory we need to execute the following commands

 

 

npm init -y

 

 

This will initialize a empty package.json file inside your project with the default options

 

Now we need to install next  and react and react-dom dependencies

 

npm i react react-dom next

 

 

 

 

Now after the command executes successfully you will see inside your package.json file the set of dependencies will be added

 

 

 

 

Now after this you need to add some scripts inside package.json like this

 

 

 

 

"scripts": {
    "dev":"next",
    "build":"next build",
    "start":"next start"
  }

 

 

 

Adding Pages in Next

 

 

Now we need to add some pages to your server side react application. So for this we need to create pages directory and inside this we need to create index.js file which will be the file for home page

Your directory structure will look like this

 

pages/index.js

 

 

 

 

 

index.js

 

 

export default () => <div>This is the Home Index Page</div>;

 

 

 

Now inside this code we are just exporting a simple react.js functional component and inside this we are writing a simple line which says this is the index page.

 

Now if you run the application on cmd by typing the command

 

npm run dev

 

Your next.js application will start at port 3000 and you will see something like this

 

 

 

 

Now if you open it on browser the address locahost:3000 you will see the following result

 

 

 

 

And similarly you can create the about.js for the about page and copy paste the following code

 

about.js

 

 

export default () => <div>This is the About Page</div>;

 

 

 

So now in order to go to the about page we need to change the url to locahost:3000/about like this and you will see the about page like this

 

 

Now after this we can edit both index.js and about.js to follow best practices for our code like this

 

 

index.js

 

 

const Index = () => (
  <div>
    <h1>Posts in JSONPlaceholder API</h1>
  </div>
);

export default Index;

 

 

about.js

 

 

const About = () => (
    <div>
        <h1>About Page of App</h1>
        <p>This is the Simple App made in Next.js</p>
    </div>
)

export default About

 

 

So in this approach we are storing the actual component code inside a separate variable namely Index and About . And lastly we are exporting it. This is a better approach of writing functional components in react and next.

 

 

 

 

 

 

Linking Pages in Next

 

 

So now we will look on how to link pages with one another in next with the help of link module which is available in it. So now we need to bring the dependency like this

 

 

import Link from "next/link";

 

 

Now after this we will use ul and li tags to wrap the Link tags which will point to Home and About Pages like this inside our both Components.

See also  React.js Hooks Random Password Generator and Manager UI with Icons in Browser Using Vanilla Javascript Full Project For Beginners

 

index.js

 

 

import Link from "next/link";

const Index = () => (
  <div>
    <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About</a>
        </Link>
      </li>
    </ul>
    <h1>Posts in JSONPlaceholder API</h1>
  </div>
);

export default Index;

 

 

about.js

 

 

import Link from "next/link";

const About = () => (
  <div>
    <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About</a>
        </Link>
      </li>
    </ul>
    <h1>About Page of App</h1>
    <p>This is the Simple App made in Next.js</p>
  </div>
);

export default About;

 

 

So if you execute this you will find something like this

 

 

 

So you will see a simple navigation of components using Link module in next. So this is so simple to do in next.

 

 

Components in Next

 

 

So now we will look at components in next.js to combat the problem of dry i.e. don’t repeat yourself in programming. In this project you will see in both the files index.js and about.js we are writing the same code in both the files. To prevent this we will create a common component called as Navbar.js inside a separate folder called as components.

 

So now create a folder called as components and inside this create a file called as Navbar.js

 

components/Navbar.js

 

 

 

 

Inside this file we will copy paste the code of Navigation Link module which we have written earlier on like this

 

Navbar.js

 

import Link from 'next/link'

const Navbar = () => (
    <div>
        <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About</a>
        </Link>
      </li>
    </ul>
    </div>
)

export default Navbar;

 

 

So now you can include this component in both the pages like this

 

index.js

 

import Navbar from '../components/Navbar'
const Index = () => (
  <div>
    <Navbar/>
    <h1>Posts in JSONPlaceholder API</h1>
  </div>
);

export default Index;

 

 

about.js

 

 

import Navbar from '../components/Navbar'

const About = () => (
  <div>
    <Navbar/>
    <h1>About Page of App</h1>
    <p>This is the Simple App made in Next.js</p>
  </div>
);

export default About;

 

 

So now if you execute the app again the result will be the same. But now we are writing less code.

 

 

Custom Styling in Next

 

 

Now we will write some custom styles to style our navbar and through this you will get to understand how to write custom styles in next

 

<style jsx>{`

// write your css code here


`}
<style>

 

 

So write inside the Navbar.js file make these changes

 

 

import Link from 'next/link'

const Navbar = () => (
    <div>
        <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About</a>
        </Link>
      </li>
    </ul>

    <style jsx>{`
    
    ul{
        list-style:none;
        display:flex;
        background:#333;
        color:#fff
    }

    li{
        font-size:18px;
        margin-right:20px;
    }

    ul li a{
        color:#fff;
        text-decoration:none;
    }
    
    `

    }

    </style>

    </div>
)

export default Navbar;

 

 

So here we are targeting ul and li and a  tags to style the navbar. So these styles will be applicable to only the Navbar component. So these are not global only component specific.

 

Now if you look at the navbar you will see something like this

 

 

 

 

Layouts in Next.js

 

 

 

Now we will look at a new concept in next.js which is layouts. Layouts are generally used to define a standard set of tags which are commonly used which is head and navbar. So we will define a common layout like this which will include all the common components inside it. So that inside the different pages we will wrap the layout as a parent so the pages will include all the components which are included in the layout.

 

To define the layout we will create a file called as Layout.js inside the components folder like this

 

 

 

Now copy paste the following code to the Layout.js file which is shown below.

 

 

import Navbar from "./Navbar";
import Head from "next/head";

const Layout = (props) => (
  <div>
    <Head>
      <title>Next.js App</title>
      <link
        rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      />
    </Head>
    <Navbar />
    {props.children}
  </div>
);

export default Layout;

 

See also  React.js Pubnub SDK Realtime Tic Tac Toe Computer AI Single or Multiplayer Board Game in Javascript Full Project For Beginners

 

So now inside this Layout.js code we will explaining each line of code

First of all we are importing the navbar component to include the navbar.js file and then we are including a second module which is Head module which allows you to write the title of the website and all the code which goes inside head tag of website. Head is a module which is available in next

Inside this head we are including the title and bootstrap cdn for including bootstrap inside our website.

Now we can include this Layout.js file in both the pages of index.js and about.js file

 

index.js

 

 

import Layout from '../components/Layout';

const Index = () => (
  <Layout>
    <h1>Posts in JSONPlaceholder API</h1>
  </Layout>
);

export default Index;

 

 

About.js

 

 

import Layout from '../components/Layout'

const About = () => (
  <Layout>
    <h1>About Page of App</h1>
    <p>This is the Simple App made in Next.js</p>
  </Layout>
);

export default About;

 

 

Now if you execute the app and see you will see bootstrap is now included

 

 

You can also see the fonts are also changed because of bootstrap. Now we can also add a container class of bootstrap to both the pages index.js and about.js

 

In order to do this we just need to make a single change to our Layout.js file and then automatically the changes will take effect in all the two pages. This is the advantage of Layout file. So open Layout.js file and modify with the below code

 

 

import Navbar from "./Navbar";
import Head from "next/head";

const Layout = (props) => (
  <div>
    <Head>
      <title>Next.js App</title>
      <link
        rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      />
    </Head>
    <Navbar />
    <div className="container">
    {props.children}
    </div>
  </div>
);

export default Layout;

 

 

So we have wrapped the {props.children} by a className container. Now if you look at app it will look something like this

 

 

 

Now after this we will be making a bootstrap navbar so just go to your Navbar component file called as Navbar.js file and modify the code to below code

 

 

Navbar.js

 

 

import Link from 'next/link';

const Navbar = () => (
  <nav className="navbar navbar-expand navbar-dark bg-dark mb-4">
    <div className="container">
      <a className="navbar-brand" href="#">Next.js</a>
      <div className="collapse navbar-collapse">
        <ul className="navbar-nav ml-auto">
          <li className="nav-item">
            <Link href="/"><a className="nav-link">Home</a></Link>
          </li>
          <li className="nav-item">
            <Link href="/about"><a className="nav-link">About</a></Link>
          </li>
        </ul>
      </div>
    </div>
  </nav>
);

export default Navbar;

 

 

Now if you see your navbar by running the app you will see something like this

 

 

 

 

Make API Call in Next

 

 

Now we will be making the api call to jsonplaceholder api using the library called as isomorphic-unfetch. First of all we need to install this library

 

npm i isomorphic-unfetch

 

 

 

Now we need to include this dependency at the top of the file like this

 

import Fetch from 'isomorphic-unfetch';

 

 

Now we will make the Fetch request to the jsonplaceholder api to fetch posts. In order to do this we need to move to index.js file and inside this we have a lifecycle method which executes every time a component is rendered.

 

Index.getInitialProps = async function() {
   // function code
}

// here Index is name of component

 

 

Every component in Next has this getInitialProps lifecycle method which gets the initial properties for that component. Here we will making the fetch request.

 

Index.getInitialProps = async function() {
    const res = await Fetch("https://jsonplaceholder.typicode.com/todos/1")

    const data = await res.json()

    console.log(data.completed)

    return {
        title:data.title,
        id:data.id,
        completed:`${data.completed}`
    }
}

 

 

Here we are making the fetch request to this url and then we are converting to json again. And lastly we are returning the title,id and completed value of that post.

Just see the complete example below.

 

import Layout from '../components/Layout';
import Fetch from 'isomorphic-unfetch';

const Index = (props) => (
  <Layout>
    <div>
    <h1>Posts in JSONPlaceholder API</h1>
    <p>Title of Post: {props.title}</p>
    <p>The id of post: {props.id}</p>
    <p>The completed value of post: {props.completed}</p>
    </div>
  </Layout>
);

Index.getInitialProps = async function() {
    const res = await Fetch("https://jsonplaceholder.typicode.com/todos/1")

    const data = await res.json()

    console.log(data.completed)

    return {
        title:data.title,
        id:data.id,
        completed:`${data.completed}`
    }
}

export default Index;

 

See also  React.js Hooks Example to Embed Google Maps API With Custom Red Markers & External Zoom Controls Using TypeScript Full Project For Beginners

 

 

 

Now we can display the post in it’s own respective component called as Post. So just create a new file called as Post.js inside the components folder.

 

components/Post.js

 

 

Post.js

 

 

const Post = (props) => (
  <div>
    <p>Title of Post: {props.title}</p>
    <p>The id of post: {props.id}</p>
    <p>The completed value of post: {props.completed}</p>
  </div>
);

export default Post;

 

 

Also inside index.js we need to call this component like this

 

index.js

 

 

import Layout from '../components/Layout';
import Fetch from 'isomorphic-unfetch';
import Post from '../components/Post'

const Index = (props) => (
  <Layout>
    <div> 
    <h1>Posts in JSONPlaceholder API</h1>
    <Post title={props.title} id={props.id} completed={props.completed}/>
    </div>
  </Layout>
);

Index.getInitialProps = async function() {
    const res = await Fetch("https://jsonplaceholder.typicode.com/todos/1")

    const data = await res.json()

    console.log(data.completed)

    return {
        title:data.title,
        id:data.id,
        completed:`${data.completed}`
    }
}

export default Index;

 

Now we can display one or more posts by using map function which is available in javascript for looping arrays just modify the source code inside index.js something like this

 

 

index.js

 

import Layout from '../components/Layout';
import Fetch from 'isomorphic-unfetch';
import Post from '../components/Post'

const Index = (props) => (
  <Layout>
    <div> 
    <h1>Posts in JSONPlaceholder API</h1>
    {props.data.map((element) => (
        <Post title={element.title} id={element.id}/>
    ))}
    </div>
  </Layout>
);

Index.getInitialProps = async function() {
    const res = await Fetch("https://jsonplaceholder.typicode.com/posts")

    const data = await res.json()

    console.log(data)

    return {
        data:data
    }
}

export default Index;

 

If you run your next app you will see list of 100 posts displayed on the screen something like this

 

 

 

 

 

Building the Next.js App For Production

 

 

Now at last we will now build the app for production. So there is a simple command which you need to execute for building the application

 

npm run build

 

 

 

Leave a Reply