loading...
Cover image for Build a complete app with React and GraphQL-1

Build a complete app with React and GraphQL-1

nabendu82 profile image Nabendu Updated on ・4 min read

We are starting a new series and it’s about the latest GraphQL. Here we built an App, with React in the frontend and GraphQL in place of REST API.

This series have been inspired by this youtube tutorial from freecodecamp. We will be using the below techs.

Our TechOur Tech

Lets start right with our App. Open up your terminal and create a directory react-graphql and then a directory server inside it. Inside the server directory do npm init to create a package.json file. Press enter for everything to choose the default option.

npm initnpm init

Next we will install express.

install expressinstall express

Now, open up your code editor and create a new file app.js in the server directory. The content for the same is below.

    const express = require('express');

    const app = express();

    app.listen(4000, () => {
        console.log('Listening at port 4000');
    });

After this go to your terminal and start the server by node app.js

express serverexpress server

But, we will not run the express server by node, but instead a npm package called nodemon. This package keeps track of any changes to our server code and restarts the server.

install nodemoninstall nodemon

We will again start our server by nodemon app.js

nodemon app.jsnodemon app.js

Next, we will install two more packages of graphql and express-graphql

graphqlgraphql

Now, create a new folder schema inside server and then a new file schema.js inside it.

schema.jsschema.js

In schema.js put the below code. Here, we are first defining a type BookType and then a query called RootQuery to query it.

    const graphql = require('graphql');

    const { GraphQLObjectType, GraphQLString, GraphQLSchema } = graphql;

    const BookType = new GraphQLObjectType({
        name: 'Book',
        fields: ( ) => ({
            id: { type: GraphQLString },
            name: { type: GraphQLString },
            genre: { type: GraphQLString }
        })
    });

    const RootQuery = new GraphQLObjectType({
        name: 'RootQueryType',
        fields: {
            book: {
                type: BookType,
                args: { id: { type: GraphQLString } },
                resolve(parent, args){
                    // code from Database

                }
            }
        }
    });

    module.exports = new GraphQLSchema({
        query: RootQuery
    });

Now, we will use the same in our app.js

    const express = require('express');
    const graphqlHTTP = require('express-graphql');
    const schema = require('./schema/schema');

    const app = express();

    app.use('/graphql', graphqlHTTP({
        schema
    }));

    app.listen(4000, () => {
        console.log('Listening at port 4000');
    });

Next, we will add some dummy data in our schema.js as our database is still not ready. And also inside our resolve, we will use find to return the book whose id have been passed as args.

    const graphql = require('graphql');

    const { GraphQLObjectType, GraphQLString, GraphQLSchema } = graphql;

    // Dummy data
    var books = [
        { name: 'Name of the Wind', genre: 'Fantasy', id: '1' },
        { name: 'Two States', genre: 'Drama', id: '2' },
        { name: 'The Long Earth', genre: 'Sci-Fi', id: '3' },
    ];

    const BookType = new GraphQLObjectType({
        name: 'Book',
        fields: ( ) => ({
            id: { type: GraphQLString },
            name: { type: GraphQLString },
            genre: { type: GraphQLString }
        })
    });

    const RootQuery = new GraphQLObjectType({
        name: 'RootQueryType',
        fields: {
            book: {
                type: BookType,
                args: { id: { type: GraphQLString } },
                resolve(parent, args){
                    // code from Database - right now dummy data
                    return books.find(item => item.id === args.id);

                }
            }
        }
    });

    module.exports = new GraphQLSchema({
        query: RootQuery
    });

Next, we will use the amazing graphiql tool to check our query as our front-end is not ready yet. We will need to configure it first in

    const express = require('express');
    const graphqlHTTP = require('express-graphql');
    const schema = require('./schema/schema');

    const app = express();

    app.use('/graphql', graphqlHTTP({
        schema,
        graphiql: true
    }));

    app.listen(4000, () => {
        console.log('Listening at port 4000');
    });

Next, go to http://localhost:4000/graphql in browser and you will see the graphiql tool.

GraphiqlGraphiql

Click on the Docs on the top right corner and you will get the documentation of the queries available to this server.

Now, we can query the GraphQL server for book with id of 2 and it will return it. We need to update the query in the editor and press play button.

id 2id 2

Same for id of 3, but don’t want id in return statement.

id 3id 3

If we query an non-existent id then we will get null

non-existent id 4non-existent id 4

This concludes part-1 of the series. You can find code till here in the github link.

Posted on by:

nabendu82 profile

Nabendu

@nabendu82

Fullstack JS dev, Upcoming Author "Gatsby Cookbook"

Discussion

pic
Editor guide
 

Hi Nebendu,

nice Tutorial. As far as I could see, you'll build an App for handeling Books? Could you tell more about the app like what should it do, for whom is it, what it would provide when its done ?

Thank you for your effort.

 

Hi labibllaca,
Thanks for going through the series. It is just a simple app, which helps us understand the concept of GraphQL, react and not have much practical use. But you can always use it to keep track of your Favorite authors and there books.