What Are Higher-order Components in React?

In react, a higher-order component (HOC) is deemed an advanced technique for reusing component logic. They are not part of the React API, but they are the model that begins from React’s compositional nature. A higher-order function takes a function as an argument and returns a function. HOC is not a feature in React or any other programming language. It is a pattern that emerged from the components nature of React. Examples of the higher-order functions are the; .map, .filter, etc. How to Define a Higher Order FunctionExample 1: Function that takes another function as an argument object FunctionThatTakesFunction extends App {     def math(a:Int, b:Int, fun:(Int,Int)=>Int):Int = fun(a,b)     val sum = math(5, 6, (a,b) => a+b)     val diff = math(10, 4, (a,b) => a-b)     println(s"sum is $sum") println(s"diff is$diff")   }  Output:  sum is 11   diff is 6  Example 2: Function that sums an array of numbers: function calculate(numbers) {    let sum = 0;    for (const number of numbers) {    sum = sum + number;     }   return sum;   }   calculate([1, 2, 4]); // => 7  Output  Sum = 7  Anonymous Functions  Before starting with higher-order functions, let us discuss anonymous functions. Anonymous functions are used in JavaScript to make the code easier to read. An anonymous function can be assigned to a variable or passed into other functions, like higher-order functions.  Anonymous functions, sometimes referred to as lambdas are often used when declaring higher-order functions or in cases where the function is only used once. The latter case is important when considering performance because it saves time and memory since anonymous functions do not need to be stored for later use.  For example, A simple anonymous function is like:  x -> x + 1  Here, the input of the function is x, and the output is x + 1.  The syntax for anonymous functions is slightly different in all languages, but it is usually written as (input) → (output).  Anonymous functions are often used because they avoid the boilerplate code associated with named function declarations. Therefore, for simple functions that do not need to be re-used across multiple places, such as the one above, an anonymous function may be more appropriate.Common Higher-Order FunctionsThere are a few higher-order functions that are essential to modern codebases. These provide a way to iterate or summarize lists of data. They make code much cleaner by dealing with common list operations instead of having to create a lot of helper code for basic list operations. The clarity in intent from using them is immensely helpful as well. Filter  The Filter is a function that accepts as an argument a test function that should return a boolean value and returns a new array with only those elements for which the test function returned true.   Map  The map is a function that turns one component into another component by adding a function to each element. It is a user's work to describe how to replace each element.  Reduce  The reduce function is a slightly different task than the previous one. It takes all the components in a group and adds them using binary values/operations to produce a single value. What are Higher Order Components?A higher-order component (HOC) is a distinctive element for reusing logic in React components. Members use one or more elements as arguments and return a new enhanced feature. Sounds familiar, right? They are similar to higher-order functions, which take some functions as an argument and produce a new function. HOCs are commonly used to compose components with shared behaviour. It combines differently from regular state-to-props patterns. Higher-Order Components(HOCS Facts)It doesn't modify or mutate components but creates new ones. They are used to compose pieces and can be reused. A pure function with no side effects and returns only a new feature. Examples of real-world HOCs:react-reduxConnect(mapStateToProps, mapDispatchToProps) (UserPage)react-routerwithRouter(UserPage)material-uiwithStyles(styles)(UserPage)Higher-Order Component StructureThe below snippet shows HOC structure in React: import React from 'react';  // Take in a component as argument InsideWrappedComponent const higherOrderwrappedComponent = (InsideWrappedComponent) => {  // And return another component    class HOC extends React.Component {      render() {        return <InsideWrappedComponent/>;      }    }    return HOC;  }; The higher-order component uses a component (InsideWrappedComponent) and returns another part inside it. As a result of this component’s logic, it can create a HOC out of that component and can be used and scaled wherever necessary. Some Points to RememberBefore using HOC, there are certain things that an individual should always keep in mind. These include the following:   Components should be pureSide effects of the HOC should be avoided. HOC should compose a component for reuse. Avoid the temptation to nutate the component passed as an argument. If the component is mutated the new behaviour would also be reflected outside the enhanced component and hence the component becomes non-reusable. Use composition instead of mutation. HOC convention namingChoosing a display name will help to debug/read the code properly. For example, if HOC is withLoadingIndicator and the input component is Component then the return component can have a display name as withLoadingIndicator(Component).Invoking HOC inside the render method should be avoidedInvoking the HOC inside the render refers to every time that the HOC component is rendered/ invoked. This results in performance degradation. It is better to invoke HOD from the outside component. Examplerender(){     const RenderedComponentDegrade = HOC(Component);     return <RenderedComponentDegrade/>;   };   Creating the HOC inside the render leads to the creation of a new component. This leads to unmounting and remounting of the component, making the descendants lose their state.   Copying static methodsIt is important to declare static methods in the class. Binding the component where the static method is defined the component would not have access to a static method   Passing refsPassing props is not possible with refs as refs are not handled by React like ordinary props. We should use forwardRef API to handle this as a solution. Advantages of Using Higher-Order ComponentsHigh order components when used properly and efficiently are easy to handle  High order components help to get rid of mutating or comoving the same logic in each component created  Using High order components makes code more readable and efficient. Due to its proper naming conventions debugging of code becomes easy. Building Higher-Order Components - By Examples (2 - 3 examples)Higher-Order Component (HOC) refers to wrapping around "normal" components. It is a function that takes as input of one component and returns another component that wraps the original component.  A simple example below would help us to easily understand how this concept works.   Example One:Step 1: Create the React.js project. npm install -g create-react-app  create-react-app my-app-react  cd my-app-react  npm start Step 2: Create a file inside the src folder called HOC.js. // HOC.js  import React, {Component} from 'react';  export default function HocExample(HocComponentExample){      return class extends Component{          render(){              return (                  <div>                      <HocComponentExample></HocComponentExample>                  </div>                );          }      }   }    Include function HocExample in the file App.js file  // App.js  import React, { Component } from 'react';  import HocExample from './HOC';  class AppExample extends Component {      render() {      return (        <div>          Higher-Order Component First Example         </div>      )    }  }  AppExample = HocExample(AppExample);  export default AppExample; Explanation First, we have created a function that is HocExample inside the HOC.js file. HocExample function accepts one argument as a component.  Component is AppExample AppExample = HocExample(AppExample ); The component is wrapped inside another React component. It is easily scalable and can be modified. It is the primary application of the Higher-Order Components. Example Two: import React from 'react';    var newDataHOC = {      data: 'Example for high order component.',     }    var MyHOCExample = ComposedComponent => class extends React.Component {      componentDidMount() {         this.setState({            data: newDataHOC.data         });      }      render() {         return <ComposedComponent {...this.props} {...this.state} />;      }   };   class MyComponent extends React.Component {      render() {         return (            <div>               < h1 >{this.props.data}</h1>            </div>         )      }   }    export default MyHOCExample(MyComponent);  Note − Data is Passed to MyComponent. The MyHOCExample is a higher-order function that passes data to MyComponent. This function takes MyComponent, enhances with newDataHOC, and returns the enhanced component that is rendered on the screen.   Using HOC would help our app to maintain easily, efficiently and also help to upgrade.  Example Three: Checking authentication using HOC A component that would be displayed if the user is logged in. Create a HOC component that checks the authentication on each render(): AuthenticatedUserComponent.js import React from "react";  export function requireAuthenticationExample(Component) {      return class AuthenticatedExampleComponent extends React.Component {          isAuthenticated() {              return this.props.isAuthenticated;          }            /**           * Render           */          render() {              const loginErrorMessage = (                  <div>                      Please <a href="/login">login</a> To view this part of the application.                  </div>              );                return (                  <div>                      { this.isAuthenticated === true ? <Component {...this.props} /> : loginErrorMessage }                  </div>              );          }      };  } export default requireAuthenticationExample; Use Higher Order Component in our components that would be hidden from anonymous users:  import React from "react";  import {requireAuthenticationExample} from "./AuthenticatedExampleComponent";  export class MyPrivateComponentExample extends React.Component {      /**       * Render       */      render() {          return (              <div>                  Viewable only to anonymous users. This is a secret search and hidden from other users.              </div>          );      }  } export default requireAuthenticationExample(MyPrivateComponentExample); Debugging HOCsHOCs debugging including printf statement Editing the source code of the application to log the application state at the appropriate points, either through print statements or a logging framework.  Compiling and running the application viewing debugging statements emitted by the application at runtime   Debugging with print statements is crude, but fast and easy. One downside is that adding a print statement inherently changes the flow of the program, which may or may not be important. Additionally, an individual print statement inherently gives no indication of where in the code it was emitted. With a small number of debugging print statements, this may not be a problem. With a large number of print statements, they can be difficult to sort out and understand.  A logging framework provides several advantages over print statements. Logging frameworks usually provide some sort of log routine, which is used to emit a message with the corresponding priority. The framework itself directs the output to some destination, along with useful information such as timestamps, the name of the class or source file that contains the log statement, and even line code line numbers.   Similarly, the logging framework can filter logged messages based on priority or logging level or disable logging at all. For this reason, in contrast to the transient nature of printf statements, logging statements are usually kept indefinitely in the codebase, making it a deployment-time decision whether to log them to a file.  Summing up Higher-order functions in JS are special functions that accept functions as arguments or return them. Furthermore, if only primitives are used by functions/components as arguments or return values, then these are first-order functions. HOC offers reusability benefits: Higher-order functions provide the core behavior itself, and with the acceptance of function as an argument you can extend that behavior.

What Are Higher-order Components in React?

7K

In react, a higher-order component (HOC) is deemed an advanced technique for reusing component logic. They are not part of the React API, but they are the model that begins from React’s compositional nature.

A higher-order function takes a function as an argument and returns a function. HOC is not a feature in React or any other programming language. It is a pattern that emerged from the components nature of React. Examples of the higher-order functions are the; .map, .filter, etc.

How to Define a Higher Order Function

Example 1: Function that takes another function as an argument

object FunctionThatTakesFunction extends App {
def math(a:Int, b:Int, fun:(Int,Int)=>Int):Int = fun(a,b)
val sum = math(5, 6, (a,b) => a+b)
val diff = math(10, 4, (a,b) => a-b)
println(s"sum is $sum") println(s"diff is$diff")
}  

Output:

sum is 11
diff is 6  

Example 2: Function that sums an array of numbers:

function calculate(numbers) {
let sum = 0;
for (const number of numbers) {
sum = sum + number;
}
return sum;
}
calculate([1, 2, 4]); // => 7  

Output

Sum = 7

Anonymous Functions

Before starting with higher-order functions, let us discuss anonymous functions. Anonymous functions are used in JavaScript to make the code easier to read. An anonymous function can be assigned to a variable or passed into other functions, like higher-order functions.

Anonymous functions, sometimes referred to as lambdas are often used when declaring higher-order functions or in cases where the function is only used once. The latter case is important when considering performance because it saves time and memory since anonymous functions do not need to be stored for later use.

For example, A simple anonymous function is like:

x -> x + 1

Here, the input of the function is x, and the output is x + 1.

The syntax for anonymous functions is slightly different in all languages, but it is usually written as (input) → (output).

Anonymous functions are often used because they avoid the boilerplate code associated with named function declarations. Therefore, for simple functions that do not need to be re-used across multiple places, such as the one above, an anonymous function may be more appropriate.

Common Higher-Order Functions

There are a few higher-order functions that are essential to modern codebases. These provide a way to iterate or summarize lists of data. They make code much cleaner by dealing with common list operations instead of having to create a lot of helper code for basic list operations. The clarity in intent from using them is immensely helpful as well.

Filter

The Filter is a function that accepts as an argument a test function that should return a boolean value and returns a new array with only those elements for which the test function returned true.

Map

The map is a function that turns one component into another component by adding a function to each element. It is a user's work to describe how to replace each element.

Reduce

The reduce function is a slightly different task than the previous one. It takes all the components in a group and adds them using binary values/operations to produce a single value.

What are Higher Order Components?

A higher-order component (HOC) is a distinctive element for reusing logic in React components. Members use one or more elements as arguments and return a new enhanced feature. Sounds familiar, right? They are similar to higher-order functions, which take some functions as an argument and produce a new function.

HOCs are commonly used to compose components with shared behaviour. It combines differently from regular state-to-props patterns.

Higher-Order Components(HOCS Facts)

1. It doesn't modify or mutate components but creates new ones.
2. They are used to compose pieces and can be reused.
3. A pure function with no side effects and returns only a new feature.

Examples of real-world HOCs:

 react-redux Connect(mapStateToProps, mapDispatchToProps) (UserPage) react-router withRouter(UserPage) material-ui withStyles(styles)(UserPage)

Higher-Order Component Structure

The below snippet shows HOC structure in React:

import React from 'react';
// Take in a component as argument InsideWrappedComponent
const higherOrderwrappedComponent = (InsideWrappedComponent) => {
// And return another component
class HOC extends React.Component {
render() {
return <InsideWrappedComponent/>;
}
}
return HOC;
}; 

The higher-order component uses a component (InsideWrappedComponent) and returns another part inside it. As a result of this component’s logic, it can create a HOC out of that component and can be used and scaled wherever necessary.

Some Points to Remember

Before using HOC, there are certain things that an individual should always keep in mind. These include the following:

Components should be pure

Side effects of the HOC should be avoided. HOC should compose a component for reuse. Avoid the temptation to nutate the component passed as an argument. If the component is mutated the new behaviour would also be reflected outside the enhanced component and hence the component becomes non-reusable. Use composition instead of mutation.

HOC convention naming

Choosing a display name will help to debug/read the code properly. For example, if HOC is withLoadingIndicator and the input component is Component then the return component can have a display name as withLoadingIndicator(Component).

Invoking HOC inside the render method should be avoided

Invoking the HOC inside the render refers to every time that the HOC component is rendered/ invoked. This results in performance degradation. It is better to invoke HOD from the outside component.

Example

render(){
};   

Creating the HOC inside the render leads to the creation of a new component. This leads to unmounting and remounting of the component, making the descendants lose their state.

Copying static methods

It is important to declare static methods in the class. Binding the component where the static method is defined the component would not have access to a static method

Passing refs

Passing props is not possible with refs as refs are not handled by React like ordinary props. We should use forwardRef API to handle this as a solution.

• High order components when used properly and efficiently are easy to handle
• High order components help to get rid of mutating or comoving the same logic in each component created
• Using High order components makes code more readable and efficient. Due to its proper naming conventions debugging of code becomes easy.

Building Higher-Order Components - By Examples (2 - 3 examples)

Higher-Order Component (HOC) refers to wrapping around "normal" components. It is a function that takes as input of one component and returns another component that wraps the original component.

A simple example below would help us to easily understand how this concept works.

Example One:

Step 1: Create the React.js project.

npm install -g create-react-app
create-react-app my-app-react
cd my-app-react
npm start 

Step 2: Create a file inside the src folder called HOC.js.

// HOC.js
import React, {Component} from 'react';
export default function HocExample(HocComponentExample){
return class extends Component{
render(){
return (
<div>
<HocComponentExample></HocComponentExample>
</div>

);
}
}
}

Include function HocExample in the file App.js file
// App.js
import React, { Component } from 'react';
import HocExample from './HOC';
class AppExample extends Component {
render() {
return (
<div>
Higher-Order Component First Example
</div>
)
}
}
AppExample = HocExample(AppExample);
export default AppExample; 

Explanation

• First, we have created a function that is HocExample inside the HOC.js file.
• HocExample function accepts one argument as a component.
• Component is AppExample
• AppExample = HocExample(AppExample );
• The component is wrapped inside another React component. It is easily scalable and can be modified. It is the primary application of the Higher-Order Components.

Example Two:

import React from 'react';
var newDataHOC = {
data: 'Example for high order component.',

}
var MyHOCExample = ComposedComponent => class extends React.Component {
componentDidMount() {
this.setState({
data: newDataHOC.data
});
}
render() {
return <ComposedComponent {...this.props} {...this.state} />;
}
};
class MyComponent extends React.Component {
render() {
return (
<div>
< h1 >{this.props.data}</h1>
</div>
)
}
}
export default MyHOCExample(MyComponent);  

Note − Data is Passed to MyComponent. The MyHOCExample is a higher-order function that passes data to MyComponent. This function takes MyComponent, enhances with newDataHOC, and returns the enhanced component that is rendered on the screen.

Using HOC would help our app to maintain easily, efficiently and also help to upgrade.

Example Three:

• Checking authentication using HOC
• A component that would be displayed if the user is logged in. Create a HOC component that checks the authentication on each render():
• AuthenticatedUserComponent.js
import React from "react";
export function requireAuthenticationExample(Component) {
return class AuthenticatedExampleComponent extends React.Component {
isAuthenticated() {
return this.props.isAuthenticated;
}

/**
* Render
*/
render() {
<div>
</div>
);

return (
<div>
{ this.isAuthenticated === true ? <Component {...this.props} /> : loginErrorMessage }
</div>
);
}
};
} 

export default requireAuthenticationExample;

Use Higher Order Component in our components that would be hidden from anonymous users:

import React from "react";
import {requireAuthenticationExample} from "./AuthenticatedExampleComponent";
export class MyPrivateComponentExample extends React.Component {
/**
* Render
*/
render() {
return (
<div>
Viewable only to anonymous users. This is a secret search and hidden from other users.
</div>
);
}
} 

export default requireAuthenticationExample(MyPrivateComponentExample);

Debugging HOCs

HOCs debugging including printf statement Editing the source code of the application to log the application state at the appropriate points, either through print statements or a logging framework.

Compiling and running the application viewing debugging statements emitted by the application at runtime

Debugging with print statements is crude, but fast and easy. One downside is that adding a print statement inherently changes the flow of the program, which may or may not be important. Additionally, an individual print statement inherently gives no indication of where in the code it was emitted. With a small number of debugging print statements, this may not be a problem. With a large number of print statements, they can be difficult to sort out and understand.

logging framework provides several advantages over print statements. Logging frameworks usually provide some sort of log routine, which is used to emit a message with the corresponding priority. The framework itself directs the output to some destination, along with useful information such as timestamps, the name of the class or source file that contains the log statement, and even line code line numbers.

Similarly, the logging framework can filter logged messages based on priority or logging level or disable logging at all. For this reason, in contrast to the transient nature of printf statements, logging statements are usually kept indefinitely in the codebase, making it a deployment-time decision whether to log them to a file.

Summing up

Higher-order functions in JS are special functions that accept functions as arguments or return them. Furthermore, if only primitives are used by functions/components as arguments or return values, then these are first-order functions. HOC offers reusability benefits: Higher-order functions provide the core behavior itself, and with the acceptance of function as an argument you can extend that behavior.

Rajesh Bhagia

Blog Author

Rajesh Bhagia is experienced campaigner in Lamp technologies and has 10 years of experience in Project Management. He has worked in Multinational companies and has handled small to very complex projects single-handedly. He started his career as Junior Programmer and has evolved in different positions including Project Manager of Projects in E-commerce Portals. Currently, he is handling one of the largest project in E-commerce Domain in MNC company which deals in nearly 9.5 million SKU's.

In his role as Project Manager at MNC company, Rajesh fosters an environment of teamwork and ensures that strategy is clearly defined while overseeing performance and maintaining morale. His strong communication and client service skills enhance his process-driven management philosophy.

Rajesh is a certified Zend Professional and has developed a flair for implementing PMP Knowledge Areas in daily work schedules. He has well understood the importance of these process and considers that using the knowledge Areas efficiently and correctly can turn projects to success. He also writes articles/blogs on Technology and Management

Angular: Add service to module Code Example

4975
Angular: Add service to module Code Example

What are services in an Angular app?Services is ... Read More

Create GraphQL API with example

Recently, GraphQL has made a lot of buzz among the developer community, and it has been receiving a lot of attention because of its dynamic nature along with its capability to fetch data, which is a lot less redundant. In this Code Tutorial, you will get to learn about what GraphQL really is, why has it created such hype amongst new-age developers, how is it different from the REST approach, and finally you will be building our own API with GraphQL along with Code Tutorials. Let’s get started!What is GraphQL? A quick primerBefore understanding what GraphQL is, let’s first understand what Query Languages are. Query Languages are computer languages that request the data from a database (called queries) to a client-side application through a server. A well-known example is Structured Query Language or SQL.Coming to GraphQL, by definition - “GraphQL is an open-source data query and manipulation language for APIs, and a runtime for fulfilling queries with existing data” (source: Wikipedia). Simply put, GraphQL is a new age Query Language developed by Facebook in 2012 that helps Application Programming Interfaces (APIs) fetch only that data which is requested by the client, and nothing else. This enormously reduces the redundant data at the API endpoint and making the requests blazing fast and developer friendly.Initially, GraphQL was an internal project of Facebook and it was created for fetching specific data and reducing network usage. In 2015, it was released publicly at the React.js conference and reference implementations and specifications of GraphQL in JavaScript were open-sourced. Later most of the programming languages adopted that. New languages like Python, Node.js, Java, C#, PHP, GO, and many more, support GraphQL.But wasn’t the same thing already being done by RESTful APIs? The answer is yes, but GraphQL is different than REST in a lot of ways.GraphQL is Client-Driven, whereas REST is Server-Driven.Queries are organized in terms of Schema and strict typecasting in GraphQL, whereas REST has Endpoints for that task.GraphQL calls Specific data with a single call. REST calls Fixed data with multiple calls.Instead of the GET, POST, PUT, DELETE operations in REST, GraphQL has Query, Mutation, and Subscription for data manipulation.Some of the other advantages of using GraphQL are:GraphQL is faster than other communication APIs.GraphQL can retreat multiple resources and results with a single request.It is easy to use complex systems and microservices with GraphQL as it unifies and hides their complexity.It offers multiple libraries and powerful tools for various projects such as GraphiQL, GraphQL Explorer, Apollo.No under and over data fetching. It fetches the amount of data that is required.The core building block of GraphQL is its schema which is used as a middle way between server and client while defining the accessibility of the data.  A GraphQL schema is written in Schema Definition Language (SDL) and refers to the exact mutations and queries that a client can execute against your data graph. It can be built with any programming language. Simply, the schema defines the type of data that can be fetched, the relationships between these types of data, and what type of queries are allowed. The most basic components of a GraphQL schema are object types. They represent a kind of object you can fetch from your service along with the fields it has. Further, schema helps the client validate their query and eliminate unavailable data or the wrong structure stage.The other two fundamental parts of GraphQL are Query and Resolver. The request to fetch a particular data is called a query and a resolver is used to tell the server from where and how to fetch the data corresponding to the given field. You can execute the GraphQL queries either by Command line or by using a GraphQL server.GraphQL works in three parts – a query to read data, a mutation to write data, and a subscription to receive real-time data over time.Now that you know the ‘What’ and ‘Where’of GraphQL, let’s dive straight into our favorite part, the development phase.Let’s Play with GraphQLTo get started with GraphQL, you need a server that serves your API and a client that connects to your service endpoints. In this section, you will learn about a step-by-step procedure of building an API using GraphQL and Express on top of Node.js. In the next section, you will be implementing these prerequisites into code and start our development for the API.Prerequisites:Understanding of GraphQLNode Package Manager (or NPM) with version 10+Knowledge of basic querying and server-side programming.We will be needing a database to store the user data and everything else that a client-side application can request for. For this, you will be using LowDB, which is a simple file based JSON database for small projects in the localhost. Then you will be needing middleware to connect our database system to the requesting frontend application. For this, you will be using the Express middleware with the GraphQL implementation of Express - the Graphql-express library. Finally, you will be making a client-side application using react which can request all the data from the local database and can perform operations on the database like read, write, and delete.So, our roadmap is simple and straightforward. Create a Database Schema > Use a middleware server to query the database > Create a frontend application to use the data. If this is too much at once for you, do not worry as this is article is being written keeping in mind that the reader is a first-timer for GraphQL and basic querying as usual. Now, let’s dive into the code.Setting up Express GraphQLLet’s begin with the basic project structure of a Node.js application. Begin a new project in a new folder.$mkdir graphql-example$ cd graphql-exampleUse NPM to intiialize a project$npm init -yInstall the required dependencies for Express, MongoDB (Mongoose), and some additional dependencies required for the function of Express.$ npm install express mongoose body-parser cors --saveApollo Server is a community-maintained open-source GraphQL server that works with all Node.js HTTP server frameworks, so next, you are going to download and save that.$npm install apollo-server-express --saveThis should’ve created a package.json and a package-lock.json file within your folder. These files contain information regarding our environment, the dependencies, and the specific versions to run those dependencies.This means our environment is ready and you can now start developing the integrated server and API. We are going to write the Schema inside the index.js file. In the index.js file, start off by writing this code.const express = require('express'); const mongoose = require('mongoose'); const schema = require('./schema'); const bodyParser = require('body-parser'); const cors = require('cors'); const { ApolloServer } = require('apollo-server-express'); const url = "mongodb://localhost:27017/moviesdb"; const connect = mongoose.connect(url, { useNewUrlParser: true }); connect.then((db) => { console.log('Connected correctly to server!'); }, (err) => { console.log(err); }); const server = new ApolloServer({ typeDefs: schema.typeDefs, resolvers: schema.resolvers }); const app = express(); app.use(bodyParser.json()); app.use('*', cors()); server.applyMiddleware({ app }); app.listen({ port: 4000 }, () => console.log(Server ready at http://localhost:4000${server.graphqlPath}));In lines number 1 to 6, you’re implementing the necessary modules. Note that here you have imported the ./schema, but you haven’t created that yet. We will be doing this in the next step.In lines number 9 to 14, you are connecting the project to the MongoDB database and logging any error you face to the console.In lines number 16 to 19, you’re creating a new Apollo Server with typeDefs and Resolver. We’ll be defining those in the ./schema later in this tutorial.In lines 21 to 26, you’re firing up the Express Server at port 4000, when you will actually be able to interact with what you’re building.GraphQL has two main principles to work: types and resolvers. We defined them in Apollo Server. We’ll import them from the file you’ll create later.Next, let’s create the file models/movie.js that’ll contain the movie-Mongoose model.const mongoose = require('mongoose'); const Schema = mongoose.Schema; const movieSchema = new Schema({     name: {        type: String,        required: true     },     rating: {        type: Number,        required: true     },     producer: {        type: String,        required: true    } }, {     timestamps: true }); var Movies = mongoose.model('Movie', movieSchema); module.exports = {Movies, movieSchema};We’re going to build a simple movie app, where you can show, add, edit, and delete movies. That way you’ll get through the basics of GraphQL, which is the main goal of this tutorial.In lines 4 to 19, you’re basically determining the schema of the database that is going to hold the data of movies. Every movie is going to have a Name and a Producer of type String and a Rating of type Number.Designing the SchemaLet’s move on to the schema.js file where you’re going to build our GraphQL API.Create a new file in the root of the folder by the name of schema.js and add the following code.const { gql } = require('apollo-server-express');   const Movie = require('./models/movie').Movies;   const typeDefs = gql     type Movie {      id: ID!      name: String!      producer: String!      rating: Float!  }  type Query {    getMovies: [Movie]    getMovie(id: ID!): Movie  }  type Mutation {      addMovie(name: String!, producer: String!, rating: Float!): Movie      updateMovie(id: ID!, name: String!, producer: String!, rating: Float): Movie      deleteMovie(id: ID!): Movie    } In this, you’re building the schema. We defined the Movie type which will have an ID, the name of the movie and the producer, and a rating of type Float. The “!” after the types shows that these fields are necessary.Unlike the REST approach of getting different tasks done at different endpoint URLs, GraphQL can create operations in a single endpoint. That is what you have done in line 11 onwards. The type Query determines the GET operations, and type Mutation determines the modification operations like POST, DELETE, etc. In getMovies, you’re returning a list of all available movies in our database, and in getMovie, you’re getting the specific movie by the ID of that movie.Now you’re going to link these with the Mongoose Database queries that are going to perform the actions in the database. And this is done by Resolvers. Resolvers are a collection of functions that connect schema fields and types to various backends. It can read, write, and delete data from and to anywhere in the database, be it SQL, NoSQL, or Graph-based database. In simple terms, they act as a GraphQL query handler. Here’s how you’re going to implement Resolvers in our code:const resolvers = {   Query: {     getMovies: (parent, args) => {       return Movie.find({});     },     getMovie: (parent, args) => {       return Movie.findById(args.id);     }   },   Mutation: {     addMovie: (parent, args) => {       let movie = new Movie({         name: args.name,         producer: args.producer,         rating: args.rating,       });       return movie.save();     },     updateMovie: (parent, args) => {       if (!args.id) return;         return Movie.findOneAndUpdate(          {            _id: args.id          },          {            $set: { name: args.name, producer: args.producer, rating: args.rating, } }, {new: true}, (err, Movie) => { if (err) { console.log('Something went wrong when updating the movie'); } else { continue; } } ); } } } module.exports = {typeDefs,resolvers};This is the basic logic of MongoDB and CRUD applications, which doesn’t come under the scope of this article, since it is majorly focused on GraphQL. However, the logic is simple and straightforward for anyone to understand, so skim through it once.With this, you’re done with a basic Movie API that can perform all the CRUD operations on a database of movies. To test this out, you’re going to fire up our node server and open the browser in http://localhost:4000/graphql which will open the GraphQL Playground.$ node index.js Server ready at http://localhost:4000/graphqlOnce the Playground UI opens, you’re first going to create a Movie Record for the database since it would initially be empty.mutation { addMovie(name: “GraphQL Movie”, producer: “Facebook”, rating:  4.5) { id, name, rating, producer } }OUTPUT:{ “data” : { “addMovie”: { “id”: “5j2j1lnk1LNS231MLK3”, “name”: “GraphQL Movie”, “producer”: “Facebook”, “rating”: 4.5 } } }And now let’s list out all the movies in the database with only their “name” and “rating”.query { getMovies: { name, rating } }OUTPUT:{ “Data”: { “getMovies”: [ { “name”: “GraphQL Movie”, “rating”: 4.5 } ] } }So, you have successfully created a Movie API where you can perform all the CRUD operations on a single endpoint, and also ask for just the data that you want.  This results in a blazing fast API response and a developer-friendly return object that makes development fast and easy.Using GraphQL with ReactUsing GraphQL with react is super easy and can make full-stack development look like a piece of cake. We’re going to build a react app that uses the Movie API you just built to render the results on a frontend client app.Start off by installing the required dependencies.\$ npm install create-react-app graphql @apollo/clientCreate a new React appnpx create-react-app movies-appLet’s start off by initializing an ApolloClient instance. In index.js let's first import the symbols you need from @apollo/client, Next, you'll initialize ApolloClient, passing its constructor a configuration object with URI and cache fields:import {   ApolloClient,   InMemoryCache,   ApolloProvider,   useQuery,   gql } from "@apollo/client"; const client = new ApolloClient({   uri: 'https://48p1r2roz4.sse.codesandbox.io',   cache: new InMemoryCache() });The URI specifies the GraphQL Server URL.That’s it! Our client app is ready to fetch data from the GraphQL server. In index.js, let’s wrap our React app with the ApolloProvider Component. Put up the ApolloProvider somewhere high in the app, above any component that might need to access GraphQL data.function App() {   return (           My first GraphQL app       ); } render(         ,   document.getElementById('root'), );With this being done, our client app is now ready to request data from the server and perform queries on the frontend. We can do this using the useQuery React Hook that shares the GraphQL data with the UI.In the index.js, let’s first define the query you want to execute.const MOVIES = gql   query getMovies {      name,      producer   } ;Next, let's define a component called GetMovies that executes our getMovies query with the useQuery hook:function GetMovies() {   const { loading, error, data } = useQuery(MOVIES);   if (loading) return Loading...;   if (error) return Error :(;   return data.map(({ name, producer }) => (                   {name}: Produced by {producer}             )); }Whenever this component renders, the useQuery hook automatically executes our query and binds the results to the data property on successful completion of the query.Finally, you'll add GetMovies to our existing component tree:function App() {   return (           My first Apollo app             ); }When your app reloads, you should briefly see a loading indicator, followed by a list of Movies present in the MongoDB database.Congratulations. You just made a React app that uses GraphQL to render data from the server. Give yourself a pat on the back for this one.Dev-friendly Query Languages are the FutureSo, wrapping it all up in a few more lines. In this tutorial, you learned what GraphQL is - a new age Query Language that is data specific and client-oriented, how is it different (and better) than REST architecture - it is developer friendly, blazing-fast, and easy to learn or understand. We also made a mock API of Movies using GraphQL and MongoDB and performed the CRUD operations using just one single endpoint URL - another benefit over the RESTful architecture. And finally, you went on to create a React application that uses these benefits of GraphQL and combines them with the benefits of React to give a hyper-fast, easy, and full-stack app that renders Movies on request.We hope you learned something new from this article. Once you’ve started this journey of GraphQL, it is a fun ride ahead since it is a relatively new tech and not many people out there are having this skill under their hood. So, make use of this opportunity and outshine the rest.Keep Learning.
4805
Create GraphQL API with example

Recently, GraphQL has made a lot of buzz among the... Read More