Data Fetching and Form Building using NextJS

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Next.js is one of the easy-to-learn frameworks for server-side pre-render pages for client-side web applications. How to get started on Next.js and build a sample site is shown in the previous blog

In this blog, we will see how we can fetch data from API and make it pre-render pages. Also, let's see how forms work in nextJs and collect the data without maintaining the database. This will be a continuation of the consulting template website created in the previous blog where the company wants to project the open-source code contribution and user interface to collect the data from the site visitors. 

Pre-rendering:

Next.js pre-renders every page which helps in performance and SEO. Pre-renders means, it creates the HTML page on the server-side and you can see that page itself coming in the network tab as shown below:

We have two types of pre-rendering, it depends on when it will be generated. If the page is generated at the build time, it is called static generation and if it is generated at the time of request it is called server-side rendering. For our use case of showing all the public open-source contributions, it needs to be dynamically fetched from Github on each request. The previous blog was an example of static generation as it was all statically generated.     

Fetching GitHub Repos:

Github provides API to fetch the repositories metadata details. It is free-to-use simple APIs, we can look at the documentation for more details. Used fetch javascript API to fetch the data and resolve the data to set that as props for the about page. 

If you export a function called getServerSideProps (Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps. Github API provides a lot of data but we show a few of the data on the screen. So returning props object with the required fields. 

export async function getServerSideProps(context) {
  const res = await fetch("https://api.github.com/users/devgroves/repos");
  const data = await res.json();
  // console.log('data', data.filter((elem) => !elem.name.includes("tutorial")));
  const filteredData = data.filter(elem => isReadyProject(elem)).map((elem) => {
    return {
      id: elem.id, name: elem.name, html_url: elem.html_url, description: elem.description, full_name: elem.full_name,
      language: elem.language, stargazers_count: elem.stargazers_count, forks: elem.forks
    };
  });
  return {
    props: {
      data: filteredData
    },
  };
}

Also, I need to project the projects which are ready to use and skip the WIP (work in progress) kind of projects. To do that, you can create a function and use it as part of the filter before mapping it. isReadyProject is a function that will filter the project. It checks the topics metadata of each repo which does not contain "wip-do-no-use". This function can be customized to your need by changing to any other GitHub parameters and do it.  

function isReadyProject(elem) {
  let topics = elem.topics;
  let result = true;
  topics.forEach((topicName) => {
    if (topicName.search("wip-do-not-use") >= 0) {
      result = false;
    }
  });
  return result;
}

Now we are going to display a list of cards layout for each repo. I am going to use react-bootstrap to make it responsive and it will be like having a card for a repository so we can loop for each repository. There will be a demo.png file in each repository in which we will show the left part of the card. Also used the react icons package to show the key things like language, stars and forks with icons as react components. 

Filename: pages/about.jsx       

<Row>
       <h3 className="repo-header">OUR Public Code Repositories For Glance</h3>
        </Row>
        <Row>
          {data &&
            data.map((val) => (
              <Col key={val.id} md={6} sm={12}>
                <Card className="repo-card">
                  <Row>
                    <Col md={4} className="projectCard">
                      <Image
                        src={`https://raw.githubusercontent.com/${val.full_name}/main/demo.png` || Image1}
                        alt="image"
                        width={300}
                        height={250}
                      />
                    </Col>
                    <Col md={6}>
                      <Card.Body>
                        <Card.Link href={val.html_url}>{val.name}</Card.Link>
                        <Card.Text className="projectCard-text">{val.description}</Card.Text>
                        <div className="projectCard-body">
                          <p>
                            <GoPrimitiveDot /> {val.language}
                          </p>
                          <p>
                            <GoStar /> Stars:{val.stargazers_count}
                          </p>
                          <p>
                            <GoRepoForked /> Forks:{val.forks}
                          </p>
                        </div>
                      </Card.Body>
                    </Col>
                  </Row>
                </Card>
              </Col>
            ))}
        </Row>

The public code repository gallery will show like below:

Working with forms:

A web form has a client-server relationship. They are used to send data handled by a web server for processing and storage. The form itself is the client, and the server is any storage mechanism that can be used to store, retrieve and send data when needed.

HTML forms are built using the <form> tag. It takes a set of attributes and fields to structure the form for features like text fields, checkboxes, dropdown menus, buttons, radio buttons, etc.

I need a contact form, so customers can do an inquiry by filling it out. It will collect the basic details like firstname, lastname, contact number, mail id, attachment and description. Thanks to W3C community, input types are specifically created for phone, email so it will work intuitively based on the data type. A simple form validation will be sufficient as it has to customer-friendly form to enter their details quickly. Client-side form validation is to check for mandatory fields, validating data types and its limits. Server-side validation is preferable for more secure validation. 

Filename : pages/contact.jsx

<Row className="center container-height zero-margin contactform-bg">
          <Col md={6} sm={12} className="mobile-container">
            <Image
              src={ContactUsImage}
              alt="Contact us image"
              height={400}
              width={600}
              placeholder="blur"
              className="imgContain"
            />
            <Breadcrumbs name="Contact us" />
          </Col>
          <Col>
            <div className="form-container">
              <form onSubmit={handleSubmit}>
                <h5>Please fill in the form, we will get back to you ... </h5>
                <Row>
                  <Col>
                    <input
                      type="text"
                      id="name"
                      name="firstname"
                      onChange={(e) => {
                        setName(e.target.value);
                      }}
                      placeholder="Your name please.."
                      height="1"
                      required
                    />
                  </Col>
                </Row>

                <Row>
                  <Col md={6} sm={12}>
                    <input
                      type="tel"
                      id="number"
                      name="number"
                      placeholder="Contact number"
                      required
                      onChange={(e) => {
                        setNumber(e.target.value);
                      }}
                    />
                  </Col>
                  <Col md={6} sm={12}>
                    <input
                      type="email"
                      id="email"
                      name="email"
                      placeholder="Email Id.."
                      required
                      onChange={(e) => {
                        setEmail(e.target.value);
                      }}
                    />
                  </Col>
                </Row>

                <Row className="formItem">
                  <Col>
                    <input
                      type="file"
                      id="file"
                      name="file"
                      placeholder="Attach Your file"
                      onChange={(e) => {
                        setFile(e.target.value);
                      }}
                    />
                  </Col>
                </Row>
                <Row>
                  <Col>
                    <textarea
                      id="subject"
                      name="subject"
                      placeholder="Please drop in your questions.."
                      required
                      onChange={(e) => {
                        setMessage(e.target.value);
                      }}
                    ></textarea>
                  </Col>
                </Row>
                <Row>
                  <Col>
                    <input type="submit" value="Submit" />
                  </Col>
                </Row>
              </form>
            </div>
          </Col>
          <p className="aligncenter">
               { showSuccess? "We noted the details, thanks for your time!": "" }
          </p>
        </Row>

On submission of the form, handleSubmit javascript function will be invoked on the client-side.  Now it collects form data as json and hit the backend API api/contact. 

const handleSubmit =async (event) => {
    event.preventDefault();
    const data = {
      "name":name,
      "email":email,
      "number":number,
      "file":file,
      "message":message
    }
    const res = await fetch("/api/contact", {
      method: "post",
      body: JSON.stringify(data),
    });
    const result = await res.json();
    setShowSuccess(true);
    setTimeout(()=> setShowSuccess(false), 2000);
    console.log("handle submit ", result);
   }

Now in the project structure, under the pages/api folder, we can create a contact API (/contact.js). In this file, we create a handler with request and response HTTP objects. Now in the request, you will receive the form data. Instead of setting up a database, collect the information and send it to the official email id. nodemailer is a simple-to-use package for sending emails. Use transporter.sendMail to send the mail with form data which returns a promise to be checked for success or failure. 

export default function handler(req, res) {
  const body = JSON.parse(req.body);
  console.log(body.message);
  const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: "test@example.com",
      pass: "XXXXXX",
    },
  });

  const mailOptions = {
    from: "test@example.com",
    to: "devgrovestechnologies@example.com",
    subject: "Contact form from devgroves",
    text: body.message,
  };

  transporter.sendMail(mailOptions, function (error, info) {
    if (error) {
      console.log(error);
    } else {
      console.log("Email sent: " + info.response);
    }
  });
  
  res.status(200).json({ status: "OK" });
}


Github project link: https://github.com/devgroves/consultingtemplatebynextjs


   

DevGroves Technologies is a IT consulting and services start-up company which is predominately to web technologies catering to static website, workflow based CRM websites, e-commerce websites and reporting websites tailoring to the customer needs. We also support open source community by writing blogs about how, why and where it need to be used for.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Build Consulting Website using Next.js

  • react nextjs website-development ssr

One of the popular web framework for building Single page application (SPA) or static site is React library. Application built with React packages will be rendered completely on the client side browser. If you want to reduce the load on client side browser, we need to pre-render the pages in server (Serer side rendering) and serve it to the client. So the client loads the page like simple html page. Also if the pages are rendered from server then search engine will be able to fetch and extract the pages. To do SSR for React, the best abstraction framework is Next.js. In this blog, we will explain how to build a simple consulting website using NextJS.

Read More


Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More


Desktop Apps using Electron JS with centralized data control

  • electronjs couchdb pouchdb desktop-app

When there is a requirement for having local storage for the desktop application context and data needs to be synchronized to central database, we can think of Electron with PouchDB having CouchDB stack. Electron can be used for cross-platform desktop apps with pouch db as local storage. It can sync those data to centralized database CouchDB seamlessly so any point desktop apps can recover or persist the data. In this article, we will go through of creation of desktop apps with ElectronJS, PouchDB and show the sync happens seamlessly with remote CouchDB.

Read More


Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


RESTEasy Advanced guide - File Upload

  • resteasy rest-api file-upload java

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the ASL 2.0.

Read More



Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More


Laravel Paypal Integration - Smart button with server-side integration

  • laravel paypal smart-button

You would have seen a lot of blogs for paypal php integration with REST api which is driven completely in the backend. For checkout, paypal provides an easy way to checkout for client side ready-to-use smart button payment. This approach will work only from the frontend, which will not be safe and difficult to reconcile as the backend does not have any information about it. Server side integration with the paypal smart button will help us to reconcile or track the payments even after some issues in the users payment journey. In this blog, we have walkthrough the paypal smart button with server side php laravel integration.

Read More


Enhancing The Experience With Android TV: Briefly About One Developer's Impressions

  • android android-tv

In my software development career, I have always been attracted to new technologies and innovative solutions. Project by project, I have been exploring something new, discovering and implementing different approaches and trying new solutions. When Android TV showed up, I set a new personal goal. I described my impressions and the overall opinion on the application development for Android TV right here. Hope you will find it useful and interesting.

Read More


Rowy - Airtable-like simplicity for managing your Firestore data

  • airtable-alternative spreedsheet admin-dashboard low-code cloud-function

Rowy an open-source platform to manage your data in an intuitive spreadsheet-like UI. Say goodbye to emailing that "vFinalFinal" Excel sheet. It helps to write Cloud Functions effortlessly in the browser, and connect to your favorite third party platforms such as SendGrid, Twilio, Algolia, Slack and more.

Read More


Understanding Web Real-Time Communication (WebRTC)

  • webrtc communication web

Web Real-Time Communication (WebRTC) is an open source project currently being developed with an aim to provide real time, peer-to-peer communication between web applications. WebRTC provides simple JavaScript APIs that help developers to easily build web applications with real time audio, video and data transfer capabilities. This blog has been written assuming that the reader has zero knowledge of how WebRTC works and hence have explained the entire working in detail using simple terms and analogies wherever possible. Let’s get started!

Read More


An Introduction to the UnQLite Embedded NoSQL Database Engine

  • database nosql embedded key-value-store

UnQLite is an embedded NoSQL database engine. It's a standard Key/Value store similar to the more popular Berkeley DB and a document-store database similar to MongoDB with a built-in scripting language called Jx9 that looks like Javascript. Unlike most other NoSQL databases, UnQLite does not have a separate server process. UnQLite reads and writes directly to ordinary disk files. A complete database with multiple collections is contained in a single disk file. The database file format is cross-platform, you can freely copy a database between 32-bit and 64-bit systems or between big-endian and little-endian architectures.

Read More


Advantages and Disadvantages of using Hibernate like ORM libraries

  • database orm

Traditionally Programmers used ODBC, JDBC, ADO etc to access database. Developers need to write SQL queries, process the result set and convert the data in the form of objects (Data model). I think most programmers would typically write a function to convert the object to query and result set to object. To overcome these difficulties, ORM provides a mechanism to directly use objects and interact with the database.

Read More


Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More


How Debuggers Work

  • golang debug

The first thing I do when I create a project is to create the debugger launch config at the `.vscode` folder. Debuggers help me to avoid putting print statements and building the program again. I always wondered how a debugger can stop the program on the line number I want and be able to inspect variables. Debugger workings have always been dark magic for me. At last, I managed to learn dark art by reading several articles and groking the source code of delve.

Read More


Blockchain Technology Will Revolutionize These Five Industries

  • blockchain security industries

Blockchain is buzzing across the world with its endless potential for disrupting a broad spectrum of the industries beyond the storage and transferring the values. Cryptocurrencies are revolutionizing variant industries and plenty of people talk about it with and their potential. Blockchain technology may have been made for bitcoins but it has immense potential for making the transactions secure and exciting. The technology is not ubiquitous but it already seems to be disrupting a huge number of the highly centralized industries that demonstrate practical use cases for changing the way businesses are done.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


10 Free services for your Website / Blog. Just plug it.

  • free website blog free-service free-resources

Each website / blog delivers useful content or service to its users. But website themselves requires some service to monitor and increase its presence. Here are few free services which could be used by Website / Blog. This will be very much helpful for small business owners.

Read More


PySpark: Installation, RDDs, MLib, Broadcast and Accumulator

  • pyspark spark python rdd big-data

We knew that Apace Spark- the most famous parallel computing model or processing the massive data set is written in Scala programming language. The Apace foundation offered a tool to support the Python in Spark which was named PySpark. The PySpark allows us to use RDDs in Python programming language through a library called Py4j. This article provides basic introduction about PySpark, RDD, MLib, Broadcase and Accumulator.

Read More


8 Best Open Source Searchengines built on top of Lucene

  • lucene solr searchengine elasticsearch

Lucene is most powerful and widely used Search engine. Here is the list of 7 search engines which is built on top of Lucene. You could imagine how powerful they are.

Read More


COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More







We have large collection of open source products. Follow the tags from Tag Cloud >>


Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.