Prisma MongoDB connection

How to configure MongoDB (local and Cloud based ) in Prisma ORM


Prisma is a Typescript based ORM for Javascript Frameworks such as React, Vuejs and Angular. It allows developers easily configure database and hand data using model classes.

Mongo DB

MongoDB is a NoSQL database for web, primarily. It is widely used in cloud based web and Mobile application.

How to configure MongoDB on Prima

In Prisma configuration file we can use preview version on MongoDB driver. The connection string can be stored in .env file (at the route of your project).

Local database

Form local database we can use the following connection string

//.env
 DATABASE_URL = mongodb://localhost:27017/blogdata?retryWrites=true&w=majority

Mongo Atlas database

For cloud based Mongo database we have to rely on the following connection.

//.env
 DATABASE_URL = mongodb+srv://admin:RRHEfMsK8zHWsGTI@cluster0.cqnll.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

schema.prisma

Finally the Prisma Schema file would look like the following,

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["mongodb"]
}

model User {

  id    String @id @default(auto()) @map("_id") @db.ObjectId

  email String

} 

Migrating DB

If you are familiar with Prisma and Schema, we used to run migrate command to update the database with model.

There is an exception for Mongo, you don’t need to Migrate, instead run npx prisma generate command after any change made to schema.

To update the model we use npx prisma db push command.

POST request in Nextjs Prisma API

How to create an API route with Prisma + Nextjs


Nextjs is a full stack framework for developing full stack applications using Reactjs. Next support all features of react, plus it offers server side and client side rendering.

Prisma is a new gen ORM for connecting and manipulating databases with ease and peace. It can be used with any Typescript supported frameworks.

API route

In Nextjs folder structure all routes comes under pages. API is a sub folder in this directory. We can create our special API route as follows

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  name: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json({ name: 'John Doe' })
}

Prisma and API

Prisma allow use to easily setup database and fetch rows we needed in our routes.

A simple user API with Prisma client will be

import { NextApiRequest, NextApiResponse } from "next";
import NextCors from "nextjs-cors";
import prisma from  '../../lib/prisma-client'
export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {
    await NextCors(req, res, {
        // Options
        methods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
        origin: "*",
        optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
    });
    if (req.method !== "POST") {
        // @ts-ignore
        const users = await prisma.user.findMany();
        return res.status(200).json({users} );
    }
    if (req.method == "POST") {
        const { name, email } = req.body;
        const newUser = await prisma.user.create({
            data: {
                email: email,
                name: name
            }
        },)
      return res.status(200).json(newUser)
    }
}

Here is a set of Prisma post which will help you configure and use the Prisma ORM.

Add background image to div in Reactjs

How to change background of a div using inline css in Reactjs


Reactjs is a frontend UI library for developing sophisticated web/native applications using Typescript/Javascript. The library is backed by Facebook and opensource community. For me it is like having a swiss knife in my tool kit.

Background

In CSS we use background:url() for adding awesome background to a div tag. How bout Reactjs style ?

We can try the inline style

style={{background:url(props.background )

This don’t work, instead throw an error. Then what we do ? Let’s, turn the ‘url and brackets ‘ into string.

style={{background:'url('+props.background +')'

and it will work as expected

Toggling state in Reactjs

How to toggle state in reactjs.


Reactjs is a frontend UI library for developing sophisticated web/native applications using Typescript/Javascript. The library is backed by Facebook and opensource community. For me it is like having a swiss knife in my tool kit.

Toggling a state

Toggling state can be necessary when switching buttons to a theme switcher. This can be done using the Javascript expression with the NOT(!) operator.

toggle: () => {
           darkTheme = true;
            darkTheme = !darkTheme;
        }

Here the darkTheme has true value and it can be invert to false using =! .

This is not a react feature, it is a plain Javascript operation.

Easiest way to handle multiple styles in Reactjs

How to use multiple style classes in a Reactjs component


Reactjs is a frontend UI library for developing sophisticated web/native applications using Typescript/Javascript. The library is backed by Facebook and opensource community. For me it is like having a swiss knife in my tool kit.

Multiple Styles

For beginners handling styles in React components could difficult. When it came to styles with hyphen (back-style) we have to rely on array syntax.

 <div className={styles['back-style']}>

So what about multiple styles ? We can use the array syntax or use the classNames package (multiple use of className property is not allowed in Reactjs as Vue 3 )

Let’s use the package

yarn add classnames

In the template / HTML use the classNames function to include multiple style classes.

import classNames from 'classNames' 
<div className={classNames('font-style','back-style','container')}

That’s all you need to know.

Sliding Login/Signup form in React

How to create a sliding login / signup form in Reactjs


Reactjs is a frontend UI library for developing sophisticated web/native applications using Typescript/Javascript. The library is backed by Facebook and opensource community. For me it is like having a swiss knife in my tool kit.

Sliding form component

The basic idea and CSS styles were adapted from the CodePen author,

@import url('https://fonts.googleapis.com/css?family=Montserrat:400,800&#39;);
.h1 {
font-weight: bold;
margin: 0;
}
.h2 {
text-align: center;
}
.p {
font-size: 14px;
font-weight: 100;
line-height: 20px;
letter-spacing: 0.5px;
margin: 20px 0 30px;
}
.span {
font-size: 12px;
}
.a {
color: #333;
font-size: 14px;
text-decoration: none;
margin: 15px 0;
}
.button {
border-radius: 20px;
border: 1px solid #FF4B2B;
background-color: #FF4B2B;
color: #FFFFFF;
font-size: 12px;
font-weight: bold;
padding: 12px 45px;
letter-spacing: 1px;
text-transform: uppercase;
transition: transform 80ms ease-in;
}
.button:active {
transform: scale(0.95);
}
.button:focus {
outline: none;
}
.button.ghost {
background-color: transparent;
border-color: #FFFFFF;
}
.form {
background-color: #FFFFFF;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
padding: 0 50px;
height: 100%;
text-align: center;
}
.input {
background-color: #eee;
border: none;
padding: 12px 15px;
margin: 8px 0;
width: 100%;
}
.container {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 14px 28px rgba(0,0,0,0.25),
0 10px 10px rgba(0,0,0,0.22);
position: relative;
overflow: hidden;
width: 768px;
max-width: 100%;
min-height: 480px;
}
.form-container {
position: absolute;
top: 0;
height: 100%;
transition: all 0.6s ease-in-out;
}
.sign-in-container {
left: 0;
width: 50%;
z-index: 2;
}
.container.right-panel-active .sign-in-container {
transform: translateX(100%);
}
.sign-up-container {
left: 0;
width: 50%;
opacity: 0;
z-index: 1;
}
.container.right-panel-active .sign-up-container {
transform: translateX(100%);
opacity: 1;
z-index: 5;
animation: show 0.6s;
}
@keyframes show {
0%, 49.99% {
opacity: 0;
z-index: 1;
}
50%, 100% {
opacity: 1;
z-index: 5;
}
}
.overlay-container {
position: absolute;
top: 0;
left: 50%;
width: 50%;
height: 100%;
overflow: hidden;
transition: transform 0.6s ease-in-out;
z-index: 100;
}
.container.right-panel-active .overlay-container{
transform: translateX(-100%);
}
.overlay {
background: #FF416C;
background: -webkit-linear-gradient(to right, #FF4B2B, #FF416C);
background: linear-gradient(to right, #FF4B2B, #FF416C);
background-repeat: no-repeat;
background-size: cover;
background-position: 0 0;
color: #FFFFFF;
position: relative;
left: -100%;
height: 100%;
width: 200%;
transform: translateX(0);
transition: transform 0.6s ease-in-out;
}
.container.right-panel-active .overlay {
transform: translateX(50%);
}
.overlay-panel {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
padding: 0 40px;
text-align: center;
top: 0;
height: 100%;
width: 50%;
transform: translateX(0);
transition: transform 0.6s ease-in-out;
}
.overlay-left {
transform: translateX(-20%);
}
.container.right-panel-active .overlay-left {
transform: translateX(0);
}
.overlay-right {
right: 0;
transform: translateX(0);
}
.container.right-panel-active .overlay-right {
transform: translateX(20%);
}
.social-container {
margin: 20px 0;
}
.social-container a {
border: 1px solid #DDDDDD;
border-radius: 50%;
display: inline-flex;
justify-content: center;
align-items: center;
margin: 0 5px;
height: 40px;
width: 40px;
}
.footer {
background-color: #222;
color: #fff;
font-size: 14px;
bottom: 0;
position: fixed;
left: 0;
right: 0;
text-align: center;
z-index: 999;
}
.footer p {
margin: 10px 0;
}
.footer i {
color: red;
}
.footer a {
color: #3c97bf;
text-decoration: none;
}
import classNames from 'classnames'
import React, { useEffect, useState } from 'react'
import styles from "../styles/login.module.css"
export default function LoginForm() {
const [panelMovementClass, setClass] = useState('right-panel-active')
const [isRightPanel, setRightPanel] = useState(true)
useEffect(() => {
isRightPanel ? setClass('right-panel-active') : setClass('')
})
return (
<div className={classNames(styles.container, styles[panelMovementClass])}>
<div className={classNames(styles['form-container'], styles['sign-up-container'])}>
<form action="#" className={styles.form} >
<h1 className={styles.h1}>Create Account</h1>
<div className={styles['social-container']}>
<a href="#" className={classNames(styles.social, styles.a)}><i className={classNames(styles.fab, styles['fa-facebook-f'])}></i></a>
<a href="#" className={classNames(styles.social, styles.a)}><i className="fab fa-google-plus-g"></i></a>
<a href="#" className={styles.social}><i className="fab fa-linkedin-in"></i></a>
</div>
<span className={styles.span}>or use your email for registration</span>
<input className={styles.input} type="text" placeholder="Name" name='name' />
<div>
</div>
<input className={styles.input} type="email" placeholder="Email" name='email' />
<input className={styles.input} type="password" placeholder="Password" name='password' />
<button className={styles.button} type='submit' >Sign Up</button>
</form>
</div>
<div className={classNames(styles['form-container'], styles['sign-in-container'])}>
<form action="#" className={styles.form} >
<h1 className={styles.h1}>Sign in</h1>
<div className={styles['social-container']}>
<a href="#" className={styles.social}><i className={classNames(styles.fab, styles['fa-facebook-f'])}></i></a>
<a href="#" className={styles.social}><i className={classNames(styles.fab, styles['fa-google-plus-g'])}></i></a>
<a href="#" className={styles.social}><i className={classNames(styles.fab, styles['fa-linkedin-in'])}></i></a>
</div>
<span className={styles.span}>or use your account</span>
<input className={styles.input} type="email" placeholder="Email" />
<input className={styles.input} type="password" placeholder="Password" />
<a href="#">Forgot your password?</a>
<button className={styles.button} type='submit'>Sign In</button>
</form>
</div>
<div className={styles['overlay-container']}>
<div className={styles.overlay}>
<div className={classNames(styles['overlay-panel'], styles['overlay-left'])}>
<h1>Welcome Back!</h1>
<p>To keep connected with us please login with your personal info</p>
<button onClick={() => setRightPanel(false)} className={classNames(styles.ghost, styles.button)} id="signIn">Sign In</button>
</div>
<div className={classNames(styles['overlay-panel'], styles['overlay-right'])}>
<h1 className={styles.h1}>Hello, Friend!</h1>
<p className={styles.p}>Enter your personal details and start journey with us</p>
<button onClick={() => setRightPanel(true)} className={classNames(styles.ghost, styles.button)} id="signUp">Sign Up</button>
</div>
</div>
</div>
</div>
)
}
view raw loginForm.tsx hosted with ❤ by GitHub
This is a simple Reactjs SlidingLoginSignUpForm Component

Looking for complete source? have a look @ My-React-Components repo

How to handle Redux async call conditionally

How make Redux async Thunk call conditionally.


In Redux Tool Kit [RTK] createThunk used to implement async calls to API. So how do we manage async call in React component ? We can make calls to reducers using dispatch, but it may cause some side effect, so it is better make the call conditionally.

Dispatching conditionally

In the extra reducer section store status state which is initially set to idle.

const initialState: someState = {
    value: [],
    status: 'idle',
};

  extraReducers: builder => {
        builder.addCase(getData.fulfilled, (state, {payload}) => {
            state.value = payload;
            state.status = 'succeeded';
        })
        builder.addCase(getData.pending, (state, {payload}) => {

            state.status = 'loading';
        })
        builder.addCase(getData.rejected, (state, {payload}) => {

            state.status = 'failed';
        })

Here getData is our async Thunk function. When the data fetch is fulfilled the value of status will be succeeded.

We only need to make the async call once, using the useEffect and the status state , can conditionally fire the dispatch.

const status = useAppSelector((state => state.post.status));
 useEffect(() => {
        if (status === 'idle') {
            dispatch(getData());
        }
    }, [status])

When ever refetch is required t, make status state to idle and the dispatch call will be made.

Custom Dialog width in React-Mui

How to toggle state in reactjs.


Reactjs is a frontend UI library for developing sophisticated web/native applications using Typescript/Javascript. The library is backed by Facebook and opensource community. For me it is like having a swiss knife in my tool kit.

Toggling a state

This is not a react feature, it is a plain Javascript operation.

How to use font Awesome Icons in React

How to use FontAwesome icons in React


Reactjs is a frontend UI library for developing sophisticated web/native applications using Typescript/Javascript. The library is backed by Facebook and opensource community. For me it is like having a swiss knife in my tool kit.

Font Awesome Icons

Font Awesome icons offer beautiful collection of icons for developing UI. This include free and pro icon collections.

You may note that the icons (FA) not showing up (using regular CSS class in React), even though they are imported in the CSS file. The solution for this React <FontAwesomeIcon/> component.

How to use React component

First up all we need to import few icon libraries and a component.

yarn add @fortawesome/react-fontawesome
yarn add @fortawesome/free-brands-svg-icons

In the component we want, can import the icons and uses with the React <FontAwesomeIcon/>.

//import icons
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faLinkedin,faFacebook,faGooglePlus  } from '@fortawesome/free-brands-svg-icons';
export default function SomeComponent(props) {
return(
<div>
 <div className={styles['social-container']}>
	<a href="#" className={styles.social}><FontAwesomeIcon  icon={faFacebook}  size="2x" /></a>
   <a href="#" className={styles.social}> <FontAwesomeIcon  icon={faGooglePlus} style={{ color: 'red' }} size="2x" /> </a>
	<a href="#" className={styles.social}> <FontAwesomeIcon  icon={faLinkedin} style={{ color: 'blue' }} size="2x" /> </a>
 </div>
</div>
)

Using the icon props we can specify, the icon name, and using size, color etc can even customize the component.

Render childrens in React component

How to render childrens in react component


You may not that with in the opening and closing tags of a component there can be other tag like div can contain table, list etc. By default React component hide all the components within.

So how to render the children ?

functional component

In the functional component at the end of the render section add

.....
return (
<div>
{props.children}
</div>

)

Class component

In the class component we have to use the this for accessing the props

.....
return (
<div>
{this.props.children}
</div>

)