Can we combine frontend and backend to make make user and deleteuser platform

144 Views Asked by At

I am combining react and graphql in a project.For that first, I have created a server of graphql

const graphql = require("graphql");
const {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLInt,
  GraphQLString,
  GraphQLList,
} = graphql;
const userData = require("../MOCK_DATA.json");

const UserType = require("./TypeDefs/UserType");
const RemoveUserType = require("./TypeDefs/RemoveUserType");

const RootQuery = new GraphQLObjectType({
  name: "RootQueryType",
  fields: {
    getAllUsers: {
      type: new GraphQLList(UserType),
      args: { id: { type: GraphQLInt } },
      resolve(parent, args) {
        return userData;
      },
    },
  },
});

const Mutation = new GraphQLObjectType({
  name: "Mutation",
  fields: {
    createUser: {
      type: UserType,
      args: {
        firstName: { type: GraphQLString },
        lastName: { type: GraphQLString },
        email: { type: GraphQLString },
        password: { type: GraphQLString },
      },
      resolve(parent, args) {
        userData.push({
          id: userData.length + 1,
          firstName: args.firstName,
          lastName: args.lastName,
          email: args.email,
          password: args.password,
        });
        return args;
      },
    },
    removeUser: {
      type: RemoveUserType,
      args: {
        id:{type: GraphQLInt},
        email: { type: GraphQLString },
        password: { type: GraphQLString },
      },
      resolve(args) {
        if(userData[args.id].email === args.email &&  userData[args.id].password === args.password ){
          console.log(userData[args.id])
            delete userData[args.id]
        }else{
            console.log("You cannot do that")
        }
        return args;
      },
    }
  },
});

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


And I have linked the client and the server with the Apollo client and apollo provider

"use client"

import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'
import Header from './components/Header'
import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
  HttpLink,
  from,
} from "@apollo/client";
import { onError } from "@apollo/client/link/error";
import GetUsers from "./components/GetUsers";
import Form from "./components/Form";

const errorLink = onError(({ graphqlErrors, networkError }:any) => {
  if (graphqlErrors) {
    graphqlErrors.map(({ message, location, path }:any) => {
      alert(`Graphql error ${message}`);
    });
  }
});
const link = from([
  errorLink,
  new HttpLink({ uri: "http://localhost:6969/graphql" }),
]);
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: link,
});



const inter = Inter({ subsets: ['latin'] })



export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>
      <ApolloProvider client={client}>
      <Header/>
        {children}
        </ApolloProvider>
      </body>
      
    </html>
  )
}

Next, I have made the mutations on client side like we will give on apollo client.

import { gql } from "@apollo/client";

export const CREATE_USER_MUTATION = gql`
  mutation createUser(
    $firstName: String!
    $lastName: String!
    $email: String!
    $password: String
  ) {
    createUser(
      firstName: $firstName
      lastName: $lastName
      email: $email
      password: $password
    ) {
      id
    }
  }
`;
export const REMOVE_USER_MUTATION = gql`
mutation removeUser(
  $id:Number!
  $email: String!
  $password: String!
){
  removeUser(
    id:$id
    email: $email
    password: $password
  )
}
`;

Lastly I have used the mutations in a react component using useMutation hook.

"use client"

import React, { useState } from "react";
import { REMOVE_USER_MUTATION } from "../GraphQL/Mutations";
import { useMutation } from "@apollo/client";


const FormForDeleteUsers = () => {
  const [id, setId] = useState(Number);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [removeUser, { error }] = useMutation(REMOVE_USER_MUTATION);

  const deleteUser = () => {
    console.log(id)
    console.log(email)
    console.log(password)
    console.log(removeUser)

    removeUser({
      variables: {
        id:id,
        email: email,
        password: password,
      },
    });
    if (error) {
      console.log(error);
    }
  };
  return (
    <div>
      <input className="py-5 px-12 rounded-sm outline-lime-400  mb-3 border-black border"
        type="text"
        placeholder="Email"
        onChange={(e) => {
          setEmail(e.target.value);
        }}
      />
       <input className="py-5 px-12 rounded-sm outline-lime-400  border-black border"
        type="text"
        placeholder="Password"
        onChange={(e) => {
          setPassword(e.target.value);
        }}
      />
       <input className="py-5 px-12 rounded-sm outline-lime-400  border-black border"
        type="text"
        placeholder="Id"
        onChange={(e) => {
          setId(e.target.value);
        }}
      />
       <button onClick={deleteUser} className="mt-5 py-5 px-16 bg-green-500 rounded-md hover:bg-lime-500"> Remove User</button>
    </div>
  )
}

export default FormForDeleteUsers

Also I forgot To add one I used express graphql to make a graphql server for backend

const express = require("express");
const app = express();
const PORT = 6969;
const { graphqlHTTP } = require("express-graphql");
const schema = require("./Schemas/index");
const cors = require("cors");

app.use(cors());
app.use(express.json());
app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    graphiql: true,
  })
);

app.listen(PORT, () => {
  console.log("Server running");
});

I will run node index.js for server and npm run dev for client and create user mutation works fine but remove user does not work it shows server error server responded with responed status 400. I have checked everything I could in the server part.Is there anything wrong in client or server part for removeUser.

1

There are 1 best solutions below

16
On

Your function signature in your resolver is missing the parent argument which is first, followed by args. Change:

resolve(args) {
  if(userData[args.id].email === args.email && 
    userData[args.id].password === args.password ){

to

resolve(parent,args) {
  if(userData[args.id].email === args.email &&
    userData[args.id].password === args.password ){

On the client, change your mutation code to:

export const REMOVE_USER_MUTATION = gql`
mutation removeUser( $id: Int!, $email: String!, $password: String! ) {
  removeUser(id: $id, email: $email, password: $password) {
    id
  }
}`;

(Please note the commas between the arguments to the GraphQL operations)