All Articles

Creating a Reddit Clone Using React and GraphQL - 07

inner peace

At this point, we manage to register a user. Now once a user successfully registers, the user needs to redirect to the home page. 

We start with adding useRouter from next/router . Then add the redirection to the home page.

router.push("/")

In the original video that I follow up to now, got an error here. But maybe because of an update of the ORM tool I didn’t get that. But at this point, it shows how to generate query manually. So let’s do it now.

First, we import the EntityManager from @mikro-orm/postgresql . Then we cast the em to EntityManager . The create the query and insert it. The complete query builder code something like this.

const result = await (em as EntityManager).createQueryBuilder(User)
                  .getKnexQuery().insert({
                    username: options.username,
                    password: hashedPassword,
                    created_at: new Date(),
                    updated_at: new Date(),
                  }).returning("*");

I need to highlight a few things here that once we use the getKnexQuery , it allows us to use all query operations. Another point is in our User entity has the property createdAt and mikroORM will add the underscore because of the CamelCase. But here we need to add it manually. Also, we are returning all the field from returning method.

So, we are all good at Register form and next, we move to complete the Login page. First, we need to add login.tsx file and login.graphql file. We can copy the code from register.tsxfile and paste in there and make some modifications. Also, copy the login mutation from GraphQL Playground and modify it to have variables.

Then run the yarn gen command. It will generate the relevant functions in graphql.tsx file.

Important points that I need to highlight that it needs to pass the object that contains username and password. Because once we hover over login method, it is expecting a UsernamePasswordInput object.

...
const response = await login({ options: values });
...

Now, we have a perfectly working Login page. Our next goal adding a NavBar to project. We can create a component and add it in there. Let’s do it now.

import { Box, Button, Flex, Link } from "@chakra-ui/react";
import React from "react";
import NextLink from "next/link";
import { useMeQuery } from "../generated/graphql";

interface NavBarProps {}

export const NavBar: React.FC<NavBarProps> = ({}) => {
  const [{ data, fetching }] = useMeQuery();

  let body = null;

  if (fetching) {
  } else if (!data?.me) {
    body = (
      <>
        <NextLink href="/login">
          <Link mr={2}>login</Link>
        </NextLink>
        <NextLink href="/register">
          <Link mr={2}>register</Link>
        </NextLink>
      </>
    );
  } else {
    // because one line no need ()
    body = (
      <Flex>
        <Box mr={2}>{data.me.username}</Box>
        <Button variant="link">logout</Button>
      </Flex>
    );
  }
  return (
    <Flex bg="tomato" p={4}>
      <Box ml={"auto"}>{body}</Box>
    </Flex>
  );
};

In here <NextLink /> is next.js implementation that supports client-side routing. Now we need to show that login and register links according to user login status. Also, we show the Username if the user logged in. Make sure to add this component to the Index component.

const Index = () => (
  <>
    <NavBar />
    <div>Hello world!!!</div>
  </>
);

We get the data from me query. First, add a me query and use yarn gen to generate the functions.

// we need to give a name to query
query Me {
  me {
    id
    username
  }
}

Then fetch the data from NavBar.

const [{ data, fetching }] = useMeQuery();

Recall with register check the difference here that we are using the first parameter that using data property and fetching status. Once we adding all the necessary things and try to logout by removing the cookie and again login and come to the main page. Maybe use will see your name will not update in there. It is because of the caching of urql . We will see what is the issue and fix that issue from my next blog post.

If you have anything to ask regarding this please leave a comment here. Also, I wrote this according to my understanding. So if any point is wrong, don’t hesitate to correct me. I really appreciate you. That’s for today friends. See you soon. Thank you.

References:

This article series based on the Ben Award - Fullstack React GraphQL TypeScript Tutorial. This is amazing tutorial and I highly recommend you to check that out.

Main image credit