Categories
Javascript Tech

Closures in JavaScript

A closure in JavaScript is a function that has access to variables in its outer scope, even after the outer function has returned. A closure is created when a function is defined inside another function and the inner function references variables in the outer function’s scope.

Closures allow you to preserve the state of a function’s variables even after the function has returned, and they can be used to create powerful and flexible functions that can be reused in different parts of your code.

Here’s a simple example of a closure in JavaScript:

function outerFunction(x) {
return function innerFunction(y) {
return x + y;
}
}

const add5 = outerFunction(5);
console.log(add5(3)); // 8

In this example, the outerFunction returns the innerFunction, which has access to the x variable in its outer scope. When we call outerFunction(5), it returns the innerFunction with x set to 5, and we assign it to the add5 variable. When we later call add5(3), it returns the result of x + y, which is 8.

Closures are an important concept in JavaScript, as they can be used to create functions that have private variables, to implement object-oriented concepts like classes and prototypes, and to manage state and data in complex applications.

Source: AI Interaction Channel

Happy Learning!

Categories
Learning Tech

How to write basic Test case for React component using Jest or Enzyme

Lets quickly straight dive into it

import React from "react";
import { shallow } from "enzyme";
import TestComponent from "./TestComponent";

describe("TestComponent", () => {
  it("renders correctly", () => {
    const wrapper = shallow(<TestComponent />);
    expect(wrapper).toMatchSnapshot();
  });

  it("contains a button", () => {
    const wrapper = shallow(<TestComponent />);
    expect(wrapper.find("button").length).toEqual(1);
  });

  it("simulates click events", () => {
    const mockCallBack = jest.fn();
    const wrapper = shallow(<TestComponent handleClick={mockCallBack} />);
    wrapper.find("button").simulate("click");
    expect(mockCallBack.mock.calls.length).toEqual(1);
  });
});

In this example, the describe block creates a test suite for the TestComponent and the it blocks define individual test cases.

The shallow function from Enzyme is used to render a shallow version of the component.

The toMatchSnapshot assertion is used to check that the component is rendering correctly.

The find method is used to locate elements within the shallow render, and the simulate method is used to trigger events on those elements.

The jest.fn function is used to create a mock callback that can be passed as a prop to the component and tested.

Happy Learning.

Categories
Learning Tech

10 Key tips on preparing for ReactJS Interview

Hello,

Lets quickly go through the 10 keys, for preparing for React Js Interview

  1. React basics: Familiarize yourself with React concepts such as components, JSX, state, props, lifecycle methods, hooks, etc.
  2. React-Redux: Understand how to use Redux with React for state management.
  3. React Router: Learn how to handle routing in React applications.
  4. React performance optimization: Know how to optimize the performance of React applications, including techniques like lazy loading, memoization, and using shouldComponentUpdate.
  5. React hooks: Knowledge of React hooks and how they can be used in place of class components.
  6. React testing: Understand how to test React components using tools like Jest and Enzyme.
  7. Familiarity with CSS: Good understanding of CSS, including CSS-in-JS solutions like styled-components.
  8. JavaScript concepts: Good understanding of JavaScript concepts like closure, asynchronous programming, and ES6 syntax.
  9. Git: Knowledge of Git and how to use it for version control.
  10. Problem solving skills: Be prepared to solve algorithmic problems and explain your thought process.

Hope you enjoy learning!

Categories
Learning Tech

Very basic of How to create a React Fiber/React Js Project from scratch

Here is the basic process to create a project with React Fiber:

  1. Install Node.js and npm (Node Package Manager) if you don’t have them installed already.
  2. Use npm to create a new React project by running the following command in your terminal or command prompt:
    npx create-react-app my-app
  3. Navigate to the newly created project directory:
    cd my-app
  4. Start the development server by running:
    npm start
  5. The development server should now be running on http://localhost:3000 in your browser.
  6. You can now start building your React Fiber application by modifying the files in the src directory.
  7. When you’re ready to deploy your application, run the following command to create a production build:
    npm run build

This should give you a basic understanding of how to create a React Fiber project. If you’re new to React, it may be helpful to go through some introductory tutorials before diving into your project.

Happy Learning!

Categories
Blog Tech

How to generate Public & Private SSH Keys on Windows?

Hello, Lets Begin.

Open a Command Prompt/Terminal Window.

Important Alert!: Before going further, there is very important to know. If you have already generated a private/public key pair, don’t do it again!.

Where to find those keys or check if generated or not?

Okay, lets quickly see that step, Open Explorer window and type in address of explorer %userprofile%/.ssh it will open the window for you.

Typing %userprofile%/.ssh

Result of opening the above path. if you already have files will be listed otherwise it would be empty, so you can continue following reading next few steps to generate up the same.

.ssh list keys if already generated on your system or otherwise it list empty

Follow steps if no keys are available in the case.

Lets go back to our open Terminal Window/Command Prompt enter command:

ssh-keygen -b 4096

You are prompted to answer a few questions.

First is “Enter file in which to save the key” Press enter to use the default location.

The next question is “Enter passphrase.” This step is optional, but good to have for better security. Use whatever you like or skip, and then press enter.

Then confirm the passphrase or enter if none.

Once done new keys will be saved to same path under .ssh

For example: C:\your-username\.ssh\id_rsa.pub

Then you can use both the files to upload it under your hosting server to make a communication with your server through terminal window.

To make a connection to hosting server from terminal windows, that’s another topic we will cover them later in new post.

Hope this solves your finding.

Happy Learning

Categories
Blog Learning Tech

How to update PHP version on shared host website or under cpanel?

Hello welcome to the post!

Look for “MultiPHP Manager” in Cpanel search bar or on home page of your Cpanel after login.

Reference screenshot

It will show you your current System PHP version and below option to change the setting for PHP version as required.

From dropdown menu like on right select the version of PHP you needed and apply, before that not to forget to select the list of domains, if you have multiple websites or subdomains to apply the latest PHP version.

Hope this solves your issue to the fastest when composer dependencies gives error like below when you trying to test small issue of your website.

{ "message": "syntax error, unexpected token \")\"", "exception": "ParseError", "file": "/home4/ininszp2/abclar/vendor/symfony/css-selector/XPath/Extension/NodeExtension.php", "line": 68, "trace": [ { "file": "/home4/ininszp2/abclar/vendor/composer/ClassLoader.php", "line": 428, "function": "Composer\\Autoload\\includeFile" }, { "file": "/home4/ininszp2/abclar/vendor/symfony/css-selector/XPath/Translator.php", "line": 56, "function": "loadClass", "class": "Composer\\Autoload\\ClassLoader", "type": "->" }, { "file": "/home4/ininszp2/abclar/vendor/symfony/css-selector/CssSelectorConverter.php", "line": 40, "function": "__construct", "class": "Symfony\\Component\\CssSelector\\XPath\\Translator", "type": "->" }, { "file": "/home4/ininszp2/abclar/vendor/tijsverkoyen/css-to-inline-styles/src/CssToInlineStyles.php", "line": 19, "function": "__construct", "class": "Symfony\\Component\\CssSelector\\CssSelectorConverter", "type": "->" }, { "file": "/home4/ininszp2/abclar/vendor/laravel/framework/src/Illuminate/Mail/Markdown.php", "line": 73, "function": "__construct", "class": "TijsVerkoyen\\CssToInlineStyles\\CssToInlineStyles", "type": "->" }, { "file": "/home4/ininszp2/abclar/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php", "line": 309, "function": "render", "class":

Thanks for reading and Happy learning!

Categories
Blog Learning Tech

how to fix Referrer Policy: strict-origin-when-cross-origin?

Hello,

I was facing this issue on the subdomain site, were subdomain accessing the assets from parent site domain.abc from folder structure pattern path of image file.

Was getting 404 error for loading image… (why I am explaining all over this, lets come to point of fixing 🙂 )

To note I was doing this under my Cpanel Shared Hosting Server.

In my root folder (mdw) of assets for example mdw/assets/images/ created .htaccess files and added following lines of code:

SetEnvIf Origin "http(s)?://(.+\.)?mywebsite\.com(:\d{1,5})?$" CORS=$0

Header set Access-Control-Allow-Origin "%{CORS}e" env=CORS
Header merge  Vary "Origin"

and the image started loading fine, CORS issue resolved.

Just in regex above replace with the exact domain name of parent it will fix the CORS issue of the question.

Beside, if you don’t have access to shared host or cpanel, then try to install browser CORS plugin and enable it to load the resources by bypassing this CORS issue, in same case it still won’t work you would need request your team or superior to get it resolved for you 🙂

Thanks for reading!

Happy Learning!

Categories
Javascript Learning Tech

What to do when you get Error: sgmail send error Bad Request (400) The attachment content must be base64 encoded. attachments.0.content for nodejs or in next js application?

Okay well, this error occurred when you try to send the generated buffer data as an attachment using @sendgrid/mail service.

To tackle issue, will simply paste the previous line of code and the fix line of code so data was then send as base64 content as required with the @sendgrid/mail service

  res.send(response); //previous line of response from nextjs api

after adding the fix over same above line using Buffer

  res.send(Buffer.from(response).toString('base64')); // to base64 string as an output resolve the above issue

If anyone wants to look for the entire piece of file code, here you go:

// import the necessary node libraries
const chromium = require('chrome-aws-lambda');
const puppeteer = require('puppeteer');
import { createEmailTemplate } from "../../api/functions/index";
// var Buffer = require('buffer/').Buffer  // note: the trailing slash is important!

export default async (req, res) => {

    // console.log({ m: req.method.toLowerCase(), body: Object.keys(req.body).length });

    if (req.method.toLowerCase() !== 'post' ||
        (!Object.keys(req.body).length ||
            process.env.YOUR_EXTERNAL_API_SECRET !== req.body.your_api_secret)) {
        res.status(403).send("Access denied");
        return;
    }

    const { generateType, store } = req.body; // && JSON.parse(JSON.streq.body);
    const templatePayload = {
        ...req.body,
        assetsBaseURL: process.env.NEXT_PUBLIC_ASSETS_BASE_URL,
        siteName: process.env.SITE_NAME,
        logoPath: store?.logo,
    };
    // console.log({ templatePayload });
    try {

        // compile the file with handlebars and inject the customerName variable
        const html = createEmailTemplate("my-invoice", templatePayload);

        // simulate a chrome browser with puppeteer and navigate to a new page
        const browser = await puppeteer.launch({
            args: chromium.args,
            // defaultViewport: chromium.defaultViewport,
            // defaultViewport: generateType && generateType === 'pdf' ? chromium.defaultViewport : { width: 640, height: 1200 }, //chromium.defaultViewport,
            executablePath: await chromium.executablePath,
            headless: generateType && generateType === 'pdf' ? true : chromium.headless,
            ignoreHTTPSErrors: true,
        });

        const page = await browser.newPage();
        await page.setViewport({
            width: 640,
            height: page.viewport().height, // + 400,
            deviceScaleFactor: 1,
        });

        // set our compiled html template as the pages content
        // then waitUntil the network is idle to make sure the content has been loaded
        await page.setContent(html, { waitUntil: 'networkidle0' });

        // convert the page to pdf with the .pdf() method
        let response;
        if (generateType && generateType === 'pdf') {
            const pdf = await page.pdf({ format: 'A4' });
            response = pdf;
        } else {
            const screenshot = await page.screenshot({ fullPage: true });
            response = screenshot;
        }
        await browser.close();

        // // send the result to the client
        res.statusCode = 200;
        res.send(Buffer.from(response).toString('base64'));

        // CODE BELOW WRITE RESPONSE AS HTML AND IMAGE IS DISPLAYED, TESTTED 
        // res.writeHead(200, { 'Content-Type': 'text/html' });
        // res.write('<html><body><img src="data:image/jpeg;base64,')
        // res.write(Buffer.from(response).toString('base64'));
        // res.end('"/></body></html>');

    } catch (err) {
        console.log(err);
        res.status(500).json({ message: err.message });
    }
};

I hope this find useful to anyone who facing this question or challenge.

Happy learning! Enjoy!

Categories
Tech

3D Printing, Laser Engraving & Cutting, CNC Service in Mira Road Mumbai

multidimensionwork #multidimwork #mdw

They provide 3D Printing, Laser Engraving and Laser Cutting on various materials like paper, wood, fabric, plastic, leather, rubber, ceramic, glass. CNC work for small or medium size art or designs.

Multidimwork having a best industry all in one 3D Printer, Laser Engraving and Cutting, CNC machine, available in your nearby area or city.

Machine work area as follow:

3D Printing (W × D × H)320 × 350 × 330 mm

Laser Engraving & Cutting (W × D)

320 × 350 mm

CNC Carving (W × D × H)

320 × 350 × 275 mm

For any inquiries you can write them at mdw@doableyo.com and best to follow them on Instagram : @multidimwork for recent work’s!

Categories
Javascript Learning Tech

How to filter customers state array based on set of array of ids in javascript/reactjs.

Filtering customers state array based on array of ids in javascscript/react.

const activeCustomerIdSet = [3,4,9];

//customers is array of customer data in my case its array value is bit different, just to note.

const filteredActiveCustomersIds = Array.from(activeCustomerIdSet) || [];
            let nonActiveCustomers = [];
            let filterCustomer = [...customers];
            if (filteredActiveCustomersIds.length) {
                for (let cid of filteredActiveCustomersIds) {
                    filterCustomer = filterCustomer?.filter(cust => {
                        if (+cust?.value?.id !== cid) {
                            
                            return cust;
                        }
                    });
                }
                nonActiveCustomers = [...nonActiveCustomers,
                    filterCustomer];
            }

            console.log({  filteredActiveCustomersIds, customers, nonActiveCustomers });

Hope you find useful in your search!

Keeping it short simple and straight.

Happy coding!