Showing posts with label React. Show all posts
Showing posts with label React. Show all posts

Tuesday, November 22, 2022

What's new in NextJS 13?

 NextJS had released the latest version of its framework NextJS 13. There are so many changes can be obviously noticed. I summaries the changes in short notes.

Folder-based Routing in NextJS 13.

1. the pages folder had been removed and replaced with app folder for routing purpose.

2. use folder for file system routing.

3. use square bracket for dynamic routing [id].tsx http://www.mywebsite.com/{id}

4. use  parenthesis to exclude the directories from routing. (excluding directory)

NextJS provide to turbo mode for fast app launching in the development machine with the following command

npx next dev --turbo 

NextJS had reserved serveral file names in NextJS 13.

  • page.tsx
  • layout.tsx
  • loading.tsx
  • error.tsx
  • template.tsx
  • head.tsx 

Update nextjs.config.js configure file to use new feature app folder instead of pages folder for file sytem routing

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: { appDir: true },
};

module.exports = nextConfig;


 Update packages.json file to enable turbo mode in development

"scripts": {
    "dev": "next dev --turbo",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },



 

 

 

 

 



 


Thursday, December 2, 2021

how to delete all node_modules in the current directory?

 when you have a specific folder to store all react projects, then there will be lots of spaces being occupied by the node_modules folder.

we can easily execute the following command to free up the space for any projects not currently working on.

E:\Code

FOR /d /r . %d in (node_modules) DO @IF EXIST "%d" rm -rf "%d"


Tuesday, August 31, 2021

how to fix the cookie is not saving in the browser storage when login mutation is called in GraphQL playground?

 when I implemented the login function, I use the express-session to handle the refresh token. one copy will be save to MongoDB, another one will be save to the cookie. However, I tested the login mutation in the Apollo GraphQL playground. the cookie had been sent in the response header, but it never save in the browser.

the root cause of this issue is sterm from the playground setting.

by default "request.credentials": "omit",  it should be "request.credentials": "include", to force the playground to save the cookie

here is the original setting of playground

{

  "editor.cursorShape": "line",

  "editor.fontFamily": "'Source Code Pro', 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace",

  "editor.fontSize": 14,

  "editor.reuseHeaders": true,

  "editor.theme": "dark",

  "general.betaUpdates": false,

  "prettier.printWidth": 80,

  "prettier.tabWidth": 2,

  "prettier.useTabs": false,

  "request.credentials": "omit",

  "schema.disableComments": true,

  "schema.polling.enable": true,

  "schema.polling.endpointFilter": "*localhost*",

  "schema.polling.interval": 2000,

  "tracing.hideTracingResponse": true,

  "queryPlan.hideQueryPlanResponse": true

}

the following is the updated configuration


{

  "editor.cursorShape": "line",

  "editor.fontFamily": "'Source Code Pro', 'Consolas', 'Inconsolata', 'Droid Sans Mono', 'Monaco', monospace",

  "editor.fontSize": 14,

  "editor.reuseHeaders": true,

  "editor.theme": "dark",

  "general.betaUpdates": false,

  "prettier.printWidth": 80,

  "prettier.tabWidth": 2,

  "prettier.useTabs": false,

  "request.credentials": "include",

  "schema.disableComments": true,

  "schema.polling.enable": true,

  "schema.polling.endpointFilter": "*localhost*",

  "schema.polling.interval": 2000,

  "tracing.hideTracingResponse": true,

  "queryPlan.hideQueryPlanResponse": true

}

Tuesday, July 20, 2021

how to access the server error mesage from axios http call?

 Here is my call from my code to log the error from axios call.

export const signUp=(formData, history)=>async(dispatch) =>{
    try{
        const {data}=await api.signUp(formData);
        dispatch({type: AUTH, data});
        history.push('/');
    }catch(error){
        console.log(error);
    }
}

in the express server I have the code to send back the error message to client.

export const signUp=async (req, res)=>{
    const {firstName, lastName, email, password, confirmPassword} = req.body;
    const existingUser=await User.findOne({email});
    if(existingUser){
        return res.status(400).json({error: "User already exist!"});
    }
    if(password !== confirmPassword){
        return res.status(400).json({error: "Password do not match"});
    }
    const salt = bcrypt.genSaltSync(10);
    const hashPassword = bcrypt.hashSync(password, salt);

    try{
        const newUser = await User.create({ firstName, lastName, email, 
            password:hashPassword, name:`${firstName} ${lastName}` });
        const token=jwt.sign({email: newUser.email, id: newUser._id}, 
            process.env.SECRET, {expiresIn: "1h"});
        res.status(200).json({result:newUser, token});

    }catch(err){
        console.error(err.message);
        res.status(500).json({message: 'Something went wrong'});
    }
}

the console only show the following error message, which is not helpful to trouble shooting and represent to the user. the status code is logged, but the error message is not shown.

 return res.status(400).json({error: "User already exist!"});

Error: Request failed with status code 400 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62)


after I change the code to log the error.response, then we can finally get the error message back

export const signUp=(formData, history)=>async(dispatch) =>{
    try{
        const {data}=await api.signUp(formData);
        dispatch({type: AUTH, data});
        history.push('/');
    }catch(error){
        console.log(error.response);
    }
}
  1. status: 400
  2. statusText: "Bad Request"











Sunday, July 18, 2021

bodyParser had been deprecated and re-added to express.json.

 Usually we use bodyParser from body-parser library to parse the json object in the express server.

after we upgrade the express library to 4.16. we should receive the following message.

The signature '(options?: OptionsJson & OptionsText & OptionsUrlencoded): NextHandleFunction' of 'bodyParser' is deprecated.ts(6387)

index.d.ts(19, 5): The declaration was marked as deprecated here.

before we use this one to limit the JSON object size.

app.use(bodyParser.urlencoded({limit:'25mb', extended:true}));
app.use(bodyParser.json({limit:'25mb'}));

currently it directly interact with express object

app.use(express.urlencoded({limit:'25mb', extended:true}));
app.use(express.json({limit:'25mb'}));


Friday, July 16, 2021

how to access FastAPI swagger UI from local development?

 It is super cool that FastAPI did provide the Swagger UI without any configuration. after I compile and launch the backend application. then I can use the following link to access the swagger.

http://localhost:8000/docs/ 







we can perform our test within this swagger, instead of using any API Client software.

Wednesday, July 14, 2021

how to pass dockerfile argument from docker-compose file?

 It should be very convenient and dynamic, if we can set our environment variable on docker build time.

since I want to turn graphql playground on and off during the production deployment, I already use the 

NODE_ENV to control the playground feature in the .env file.

in .net file

NODE_ENV=dev

GraphQLModule.forRoot({
      playground: process.env.NODE_ENV === 'dev',
      debug: process.env.NODE_ENV === 'dev',
      autoSchemaFile: true,
    }),


we can use ARG to set a variable in the dockerfile that we can pass in during docker build run.

ARG node_env_var
ENV NODE_ENV=$node_env_var
RUN echo $node_env_var

here is the full content of Dockfile

FROM node:14 as production

ARG node_env_var
ENV NODE_ENV=$node_env_var
RUN echo $node_env_var

WORKDIR /usr/src/api

COPY package.json .
COPY yarn.lock .

RUN yarn global add @nestjs/cli

RUN yarn install --production=true

## install NIC s a computer networking utility for reading from and 
# writing to network connections using TCP or UDP.
RUN apt-get -q update && apt-get -qy install netcat

COPY . .

RUN yarn build

CMD ["sh", "-c", "yarn typeorm migration:run && yarn start:prod"]



in the Docker-compose.yml file we can set the args variable. when I run the deployment in the production environment, i can simply change the node_env_var: production

build: 
            context: server
            target: production
            dockerfile: Dockerfile
            args:
                node_env_var: dev

here is the docker-compse.yml file

version: "3.8"

services:
    mysqldb:
        image: mysql
        environment: 
            - MYSQL_ROOT_PASSWORD=Mys0l@123456
            - MYSQL_DATABASE=hyrecar
        ports: 
            - 3306:3306
        command: --default-authentication-plugin=mysql_native_password
        networks:
            - shared-network
        volumes: 
            - db-config:/etc/mysql
            - db-data:/var/lib/mysql
            - ./db/backup/files:/data_backup/data
       
    #acting as a proxy

    nginx:
        image: nginx:latest
        container_name: nginx-prod
        volumes: 
            - ./nginx/nginx.conf:/etc/nginx/nginx.conf
        ports: 
            - 81:80
        command: /bin/sh -c "nginx -g 'daemon off;'"    
        depends_on: 
            api-prod:
                condition: service_healthy
            app-prod:
                condition: service_started
        networks: 
            - shared-network

    api-prod:
        container_name: nestjs_api_prod
        image: nestjs_api_prod:1.0.0.0
        build: 
            context: server
            target: production
            dockerfile: Dockerfile
            args:
                node_env_var: dev
        command: sh -c './bin/wait-for -t 0 mysqldb:3306 -- yarn start:prod'
        depends_on: 
            - mysqldb
        networks: 
            - shared-network
        ports: 
            - 9000:9000
        restart: unless-stopped
        healthcheck:
            test: ["CMD", "curl", "http://api-prod:9000"]
            interval: 5s
            timeout: 3s
            retries: 6     
        
    app-prod:
        container_name: rect_app_prod
        image: rect_app_prod:1.0.0
        build:
            context: web
            target: production
            dockerfile: Dockerfile
        command: yarn run start:prod
        ports: 
            - 3000:3000
        networks: 
            - shared-network
        restart: unless-stopped

#intialize network
networks: 
    shared-network:

#Initializing docker compose volumes
volumes: 
    db-config:
    db-data:


for development and test environment deployment.

set node_env_var: dev in docker-compose.yml 

run docker-compose build to rebuilt the container

execute docker-compose up to run all containers

in the production, we just need to change node_env_var: production

then we can run docker-compose build & docker-compose up to turn off graphql playground feature for security reason.

 Please Note you can not simply update the variable in the docker-compose yaml file and run docker-compose up since the variable is passing in at docker-compose build time, not the run time. so We have to run docker-compose build process to take the effect.



Monday, July 12, 2021

handy timeout function to test for loading functionality?

During the development, we will add a loading indicator to the page to notify the user that data is loading.

however, the local environment might be able to test loading indicator since the speed is too fast.

the alternative way to do so is to add a small time out function to hold the execution of data loading function. then we can check the indicator will be shown or not.

const wait = (timeout: number) => new Promise((rs) => setTimeout(rs, timeout));

then we can use it in the data loading function 

 await wait(6000);

The data loading function will be paused for 6 second. That is enough for us to see the loading indicator spinning in the page.

I recommand to add this package to your project for loading indicator.

yarn add react-spinners

import MoonLoader from "react-spinners/MoonLoader";

add this to the render section

 <MoonLoader loading size={20} />






how to fix the a component or section is not show in React on launch or refreshing the browser?

 I use React-Carousel to implement a carousel for my app. however i found something is weird. the carousel is functiong well during the run. However I refresh the browser with F5 key, the carousel disappear. here is the snippet of code for the carousel.

 return <CarContainer>

             <Carousel value={current} onChange={setCurrent} slides={
cars.map(item=><Car {...item} />)}
            plugins={[
                "clickToChange",
                {
                  resolve: slidesToShowPlugin,
                  options: {
                    numberOfSlides: 3,
                  },
                },
              ]}
              
              breakpoints={{
                640: {
                  plugins: [
                    "clickToChange",
                    {
                      resolve: slidesToShowPlugin,
                      options: {
                        numberOfSlides: 1,
                      },
                    },
                  ],
                },
                900: {
                  plugins: [
                    {
                      resolve: slidesToShowPlugin,
                      options: {
                        numberOfSlides: 2,
                      },
                    },
                  ],
                },
              }}
            /><Dots value={current} onChange={setCurrent} number={numberOfDots}/>
        </CarContainer>
the root cause of this issue is that the cars object is still null, whenn it 
render during the refresh.
slides={cars.map(item=><Car {...item} />)}
the safe way and best practice is to make sure the data is ready before the 
component rendering. since the component will not render after the data 
is ready, unless we update the cars object in the useEffect hook. 
We can either check if cars object is null return null to prevent the 
carousel render. if(!cars) return null;
or we can use the inline conditional expression wiht logical && operator.

 return cars && <CarContainer>

             <Carousel value={current} onChange={setCurrent} slides={
cars.map(item=><Car {...item} />)}
            plugins={[
                "clickToChange",
                {
                  resolve: slidesToShowPlugin,
                  options: {
                    numberOfSlides: 3,
                  },
                },
              ]}
              
              breakpoints={{
                640: {
                  plugins: [
                    "clickToChange",
                    {
                      resolve: slidesToShowPlugin,
                      options: {
                        numberOfSlides: 1,
                      },
                    },
                  ],
                },
                900: {
                  plugins: [
                    {
                      resolve: slidesToShowPlugin,
                      options: {
                        numberOfSlides: 2,
                      },
                    },
                  ],
                },
              }}
        /><Dots value={current} onChange={setCurrent} number={numberOfDots}/>
        </CarContainer>

Saturday, July 10, 2021

the guide to setup NestJS, TypeORM, MySQL,GraphQL for Backend Development

 here is a step to follow in order to setup a backend development with TypeORM, MySQL

1. install NestJS CLI

    yarn add -g @nestjs/cli

2. create a nestjs app

    nest new my-project

3. install @nestjs/typerom typreorm mysql2 (mysql 2 is much typescript friendly than mysql)

    yarn add @nestjs/typeorm typeorm mysql2 

4. create a TypeORM config JSON file to store typeorm configuation.

    touch ormconfig.json

5. paste the following into the ormconfig.json file

    {

   "type": "mysql",
   "host": "localhost",
   "port": 3306,
   "username": "test",
   "password": "test",
   "database": "test",
   "synchronize": true,
   "logging": false,
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ]
}

6. add @nestjs/config package to the project so that we can use ConfigureModule module to access the configuration file.

    yarn add @nestjs/config 

7.  add a database module to the project

    touch database.module.ts

8. add the following code the database.module.ts to setup the database connection.

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';

@Module({
  imports: [TypeOrmModule.forRoot()],
  exports: [TypeOrmModule],
})
export class DatabaseModule {
  constructor(connection: Connection) {
    if (connection.isConnected) {
      console.log('DB connected Successfully');
    }
  }
}

9. add DatabaseModule to the app.module.ts file    

import { Module } from '@nestjs/common';

import { ConfigModule } from '@nestjs/config';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DatabaseModule } from './database/database.module';

@Module({
  imports: [ConfigModule.forRoot(), DatabaseModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}


10. execute yarn start to launch the project and you will see the DB connection had been established.

DB connected Successfully

[Nest] 16320  - 2021-07-10, 9:02:02 p.m.     LOG [InstanceLoader] TypeOrmCoreModule dependencies initialized +26ms

[Nest] 16320  - 2021-07-10, 9:02:02 p.m.     LOG [InstanceLoader] DatabaseModule dependencies initialized +1ms

[Nest] 16320  - 2021-07-10, 9:02:02 p.m.     LOG [RoutesResolver] AppController {/}: +5ms

[Nest] 16320  - 2021-07-10, 9:02:02 p.m.     LOG [RouterExplorer] Mapped {/, GET} route +3ms

[Nest] 16320  - 2021-07-10, 9:02:02 p.m.     LOG [NestApplication] Nest application successfully started +2ms

11. add Graphql to the project

yarn add @nestjs/graphql graphql-tools graphql apollo-server-express

you might encounter  missing package errors here, you can manually add them as following

yarn add ts-morph @apollo/gateway


12. add GraphQLModule to the app.module.ts to initialze GraphQL Module

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { GraphQLModule } from '@nestjs/graphql';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ComponentModule } from './components/comonents.module';
import { DatabaseModule } from './database/database.module';

@Module({
  imports: [
    ConfigModule.forRoot(),
    DatabaseModule,
    GraphQLModule.forRoot({
      playground: process.env.NODE_DEV === 'dev',
      debug: process.env.NODE_DEV === 'dev',
      autoSchemaFile: true,
    }),
    ComponentModule,
  ],
  controllers: [AppController],
  providers: [AppService],

})
export class AppModule {}


Further reading

NestJS Dccument

TypeORM - Amazing ORM for TypeScript and JavaScript ES7



 


How to fix typescript error in react-carousel Breakpoints section configuration?

i try to use react-carousel to implement a carousel for a component rotation.

here is my snippet of code

 <Carousel value={current} onChange={setCurrent} slides={cars}
            plugins={[
                "clickToChange",
                {
                  resolve: slidesToShowPlugin,
                  options: {
                    numberOfSlides: 3,
                  },
                },
              ]}
              
              breakpoints={{
                640: {
                  plugins: [
                    "clickToChange",
                    {
                      resolve: slidesToShowPlugin,
                      options: {
                        numberOfSlides: 1,
                      },
                    },
                  ],
                },
                900: {
                  plugins: [
                    {
                      resolve: slidesToShowPlugin,
                      options: {
                        numberOfSlides: 2,
                      },
                    },
                  ],
                },
              }}
            /><Dots value={current} onChange={setCurrent} number={numberOfDots}/>

however, there is an error indicator to show that there is a problem with No overload matches for this call. 


TypeScript error in /home/yang/pfc_frontend/src/components/YACarousel/index.tsx(23,11):

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<CarouselProps>): default', gave the 
following error.Type '{ 640: { plugins: { resolve: CarouselPluginFunc; options: { 
numberOfSlides: number; }; }[]; }; 900: { plugins: { resolve: CarouselPluginFunc; 
options: { numberOfSlides:number; }; }[]; }; }' is not assignable to type  
'Pick<CarouselProps, "className" | "offset" | "onChange" | "draggable" | "value" | 
"plugins" | "itemWidth" | "slides" | "animationSpeed">'.
      Object literal may only specify known properties, and '640' does not exist in type 
'Pick<CarouselProps, "className" | "offset" | "onChange" | "draggable" | "value" | 
"plugins" | "itemWidth" | "slides" | "animationSpeed">'.
  Overload 2 of 2, '(props: CarouselProps, context?: any): default', gave the following 
error.
    Type '{ 640: { plugins: { resolve: CarouselPluginFunc; options: { numberOfSlides: 
number; }; }[]; }; 900: { plugins: { resolve: CarouselPluginFunc; options: { 
numberOfSlides: number; }; }[]; }; }' is not assignable to type 'Pick<CarouselProps, 
"className" | "offset" | "onChange" | "draggable" | "value" | "plugins" | "itemWidth" | 
"slides" | "animationSpeed">'.
      Object literal may only specify known properties, and '640' does not exist in type 
'Pick<CarouselProps, "className" | "offset" | "onChange" | "draggable" | "value" | 
"plugins" | "itemWidth" | "slides" | "animationSpeed">'.  TS2769

    21 |         itemWidth={400}
    22 |         breakpoints={{
  > 23 |           640: {
       |           ^
    24 |             plugins: [
    25 |               {
    26 |                 resolve: slidesToShowPlugin,

this error stems from the typescript configuration. it did not properly get the type for 
react-carousel.as a result, the visual studio cannot recognize the syntax.
we have to import the module manually by creating a react-carousel.d.ts file and put the 
following line into the file. so that the typescript can proper understand it.

declare module "@brainhubeu/react-carousel";




Wednesday, June 23, 2021

best visual studio extension for react developer

 if you are a React developer, you definitely like to have the following extension install in your visual studio. these extensions will easily help you on React application development.

  • Auto Rename Tag
  • Bracket Pair Colorizer
  • ES7 React/Redux/React-Native/JS snippets
  • Highlight Matching Tag
  • Indent-Raibow
  • Tabnine AI Code Completion, autocomplete JavaScript, Python, TypeScript, PHP, Go, Java, Ruby, C/C++, HTML/CSS, C#, Rust, SQL, Bash, Kotlin, React, Swift, Scala, Sass, Perl, Objective C, Node JS, Matla
  • Quokka
  • Paste JSON as code

Sunday, January 17, 2021

how to quickly fix "future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed "javascript:void(0)"

 when we implement a click event to trigger api call or dispatch an action in redux, we will like to use this simple syntax to handle it.

<a href="javascript:void(0)" onClick={clearFilter}>all posts</a>

we will see the following warming in the development tool windows


since React 16.9 update had deprecate the JavaScript URL, you can check out this link for more information

https://reactjs.org/blog/2019/08/08/react-v16.9.0.html

but the work around is quiet simple. we can fix it withe code below.

<a href="#" onClick={ev => {
            ev.preventDefault();
           clearFilter
            return false; // old browsers, may not be needed
            }}>all posts</a>