Categories
Blog Javascript Learning

Solution: TypeError: Failed to construct ‘URL’: Invalid URL

Hello,

If you are facing error :


Unhandled Runtime Error
TypeError: Failed to construct 'URL': Invalid URL
Failed to construct ‘URL’ : Invalid URL in your nextjs app

And you already have following loader ‘imgix’ settings in your next.config.js file

images: {
    // loader and path setting for android build to load nextjsimage and also on web on certain scenarios!
    loader: 'imgix',
    path: '/', // Remove the path prefix for production images
    domains: [
      'xxx.com',
      '*.xxx.com',
      'aaa.xxx.com',
      'via.placeholder.com',
    ],
}

To fix this the solution provided here worked out well!

Code snippet solution: source page stackoverflow

const loaderProp =({ src }) => {
    return src;
}

<Image
      src={currentImage.imageurl}
      alt={currentImage.imageurl} 
      layout="fill"
      className={styles.imageSize} 
      loader={loaderProp}
/>

we just need to add loader prop to the Image tag of next.js component and passdown the callback function which resolves the error above, voila!

Hope this also help you if you are facing this solution in your next.js application.

happy learning!

Categories
Javascript Learning Tech

Function getStaticPaths, How to create paths in getStaticProps function If you have no access to create paths in getStaticPaths, NEXTJS

Hello,

Hope this is very interesting question of scenario you might be facing to solve with next js and

  • when you don’t want to use “function getServerSideProps” to pass dynamic (data as) props to the page components
  • when you don’t want too make a extra API calls to generate the paths for products or whatever list of thing you are creating in “function getStaticPaths”

Here is the quick things we need to work out to work this out of box for specially the scenario were are showing product detail view page which is of route like in Nextjs as “page/product/[id].js

First in function getStaticPaths() we just need to do this and pass fallback as “true” as we our dynamic path is not pre-rendered!

export async function getStaticPaths() {
    // Empty array since paths will be dynamically created in getStaticProps
    return {
        paths: [],
        fallback: true, // Set to true if there are dynamic paths that are not pre-rendered !! 
    };
};

Next, we need to edit our “getStaticProps” function and then voila;


export async function getStaticProps({ params }) {
    const product = await getProduct(params && params.id);
    if (!product) {
        return {
            redirect: {
                destination: '/',
                permanent: false,
            },
        }
    }

    return {
        props: {
            product,
            error: resp.error ? true : false
        }
    };
}

Boom you are done, and just use those props in your page component like



return (<PhotoProvider
        key={'photoprovider-key-' + product?.id}
        speed={() => 600}
        easing={(type) => (type === 2 ? '' : 'cubic-bezier(.25, 1, .30, 1)')}>

/*...other codes*/
</PhotoProvider>

you will find you page up and working, fine!

Hope this simple steps helps to solve our complex situations arises in the development work of software building on planet earth!

I would also like to the above situation, why we can’t just do the same thing simply with getServerSideProps in single function, I am facing the issue to build using next build && next export for android package, as dynamics cannot be rendered as html files due to getServerSideProps sitting in between, and also as per the Next JS docs we can’t do anything what I have found of my learnings.

Happy Learning! Thanks for reading.

Keep coding & Develop Wonderful.

To Follow help out to know: uidevwork

Categories
Javascript Learning Tech

What is forwardRef and how its helps in react?

Hello, lets quickly take a review on React forwardRef, what it in actual,

In React, the forwardRef function is a utility that allows you to pass a ref through a component to one of its children. It’s commonly used when you need to access the underlying DOM node or React component instance of a child component from the parent component.

When you create a component using functional components in React, you can use the useRef hook to create a ref object. This ref object can then be passed as a prop to child components. However, when you pass the ref as a prop to a child component, React does not automatically pass it down to the underlying DOM element or custom component. This is where forwardRef comes into play.

By using forwardRef, you can create a component that accepts a ref and forwards it to one of its children. Here’s an example:

const ChildComp = React.forwardRef((props, ref) => {
  // Use the ref object to access the underlying DOM node or component instance
  return <input ref={ref} />;
});

const ParentComp = () => {
  const inputRef = React.useRef(null);

  const handleClick = () => {
    // Access the input element using the ref
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <ChildComponent ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

In the example above, the ChildComponent uses forwardRef to forward the ref prop to the <input> element. In the ParentComponent, a ref is created using the useRef hook and passed to ChildComponent using the ref prop. This allows the ParentComponent to access the input element and call the focus method when the button is clicked.

By using forwardRef, helps to bridge the gap between functional components and the imperative DOM or component operations that sometimes require direct access to child component element.

Note here we are accessing child’s component dom node not child component here as ref object, i.e can be consider as subtle difference to understand for our mind.

Hope this helps to clear out the basic concept behind using forwardRef in React.

Happy Learning!

Categories
Javascript Learning Tech

How to fix nextjs appending http://localhost:3000/_next/image? to the image srcset how to remove for production build for images?

Hello,

Welcome to the question and for the search, facing this issue? lets quickly see how we can fix this, with and in next.config.js file.

In Next.js, when using the next/image component, the src attribute is automatically transformed to a URL that goes through the Next.js image optimization pipeline. During development, this URL may include http://localhost:3000/_next/image? to indicate the local development server.

However, for production images, you can configure Next.js to remove the http://localhost:3000/_next/image? prefix. Here’s how you can achieve that:

Create a custom loader for Next.js images:

  • Open next.config.js and add the following code:
    • module.exports = {
    • images: {
      • loader: 'imgix',
      • path: '', // Remove the path prefix for production images
    • }, };
  • This configuration sets the loader option to use the imgix loader, which removes the http://localhost:3000/_next/image? prefix. The path option is set to an empty string, this will leave the prefix for image urls and left blank

Now you can easily build your project and test to images are loading fine with absolute url path if applied so.

Hope this help to solve the issue.

Happy Learning!

Categories
Javascript Learning

How to fix Uncaught TypeError: Cannot assign to read only property ‘0’ of object occurring in JavaScript?

Hello,

This type error mostly get in scenario when you try to sort the readyonly data array.

For me this was occoured when I tried to sort the direct result from my GraphQL query response data like below:

const sortedData = data.bhangarwalas.sort((a, b) => a?.firstname > b?.firstname ? 1 : -1);

In above, data.bhangarwalas is graphql query response results which is readonly in nature as response.

To fix this issue the solution is quick fix for which I have too google to know the result!

Error Screenshot Uncaught TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’

Here is the quick solution:

const sortedData = [...data.bhangarwalas];
      sortedData.sort((a, b) => a?.firstname > b?.firstname ? 1 : -1);

In code above, We need to clone or you in other words, copying the “data.bhangarwalas” into new array variable and then over that variable, we need to perform sorting operation, which results us right response.

Hope this help you to solve the quick error or to know what scenario this type of error is generated.

Thanks for reading.

Happy learning!

Categories
Javascript Learning Tech

What to do when you get nextjs error (Module not found: Error: Can’t resolve ‘private-next-pages/’ in ‘/vercel/path0’) on vercel/nextjs deployment?

Hello,

If you too facing this error : Module not found: Error: Can’t resolve ‘private-next-pages/’ in ‘/vercel/path0’

while deploying your NextJs project over Vercel platform, please follow what solution and mistake I was doing.

Error Screenshot of error occurring from the NextJs Project deployment on vercel platform.

As, I tried to debug this error by right away check the the next in the log highlighted (in screenshot above) recommending to following alias rule to be set if you have touched you next.config.js file with any webpack settings.

In my case I did have to touched the next.config.js file and so I have add the same lines of code recommend in the follow link of Next.js doc

https://nextjs.org/docs/messages/invalid-resolve-alias

But for me still I didn’t found the right solution, because was in the naming of folder under nextjs project.

Basically, I was loading the static content into the dynamic route in Nextjs (Like example reference here).

What I have missed was the name of the folder under pages directory I have created named as “learn” it should be similar to name “posts” as created one at root level of the project to hold the “.md” or “.html” file content to pass down to dynamic route page which will be under /pages/posts/[id].js

Sharing here screenshot of the directory where the naming was a mistake

Here highlighted “learn” folder should be same as “posts” below

After renaming the folder name “learn” to “posts” the error went off and found my deployment working successfully.

Hope this small mistake tip help you to solve this problem.

If you have found any mistake in the post. Please don’t hesitate to hit me on my email jat@doableyo.com to rectify.

Enjoyed reading this? How about sharing with your friends or in groups, this would help!

Thanks, Happy Learning!

Categories
Javascript Tech

What is Event Loop & Micro and Macro Tasks in JavaScript?

Hello,

The basic concept behind the event loop working in Javascript engine!

Event Loop is a mechanism in JavaScript that handles asynchronous tasks in a non-blocking way. When JavaScript code is executed, it is run inside an event loop, which continuously checks if there are any tasks to be executed in the queue. The event loop is responsible for running the tasks in the queue, and it does this in a specific order.

The Event Loop in JavaScript has two main components: the Call Stack and the Callback Queue. The Call Stack is responsible for keeping track of the execution of the synchronous code. When a function is called, it is added to the top of the call stack, and when the function returns, it is removed from the top of the call stack.

The Callback Queue, on the other hand, is responsible for keeping track of the asynchronous tasks. When an asynchronous task is completed, it is added to the Callback Queue. The event loop continuously checks the Callback Queue to see if there are any tasks that can be executed. If there is a task, it is moved to the Call Stack, where it is executed.

Microtasks and Macrotasks are two types of tasks in JavaScript that are executed by the event loop.

Microtasks are tasks that are executed immediately after the current task has completed. Microtasks are executed before the next rendering of the web page, which means that they have a higher priority than Macrotasks. Some examples of Microtasks include Promises, MutationObserver, and process.nextTick in Node.js.

Macrotasks, on the other hand, are tasks that are executed after all the Microtasks have been executed. Macrotasks include tasks such as setTimeout, setInterval, and I/O operations in Node.js.

In summary, the Event Loop in JavaScript is responsible for handling asynchronous tasks in a non-blocking way. The Event Loop has two main components, the Call Stack and the Callback Queue. Microtasks and Macrotasks are two types of tasks that are executed by the event loop, and they have different priorities. Microtasks are executed before Macrotasks and are used for tasks that need to be executed immediately after the current task has completed, while Macrotasks are used for tasks that can be executed at a later time.

Source: AI Interaction Channels

Happy Learning!

Categories
Javascript Tech

How to identify closed 5km range co ordinates from given co ordinates

Hello,

This nice question and other below I have learned recently! Let see how its answered.

To identify the closed 5km range coordinates from a given set of coordinates, you need to first calculate the difference in latitude and longitude between the given coordinates and find the minimum and maximum values.

Here’s the basic formula:

Latitude range:

  • min latitude = given latitude – (5 / 111.2)
  • max latitude = given latitude + (5 / 111.2)

Longitude range:

  • min longitude = given longitude – (5 / (111.2 * cos(given latitude)))
  • max longitude = given longitude + (5 / (111.2 * cos(given latitude)))

Note: In the above formula, (5 / 111.2) is used to convert 5km to degrees. The value of 111.2 is the approximate number of km per degree of latitude. The value of (111.2 * cos(given latitude)) is used to convert 5km to degrees of longitude.

Once you have calculated the minimum and maximum values of latitude and longitude, you can create a bounding box by combining them. The coordinates within this bounding box would be considered as closed within a 5km range of the given coordinates.

Can you tell me more on last results?

Sure! The last results I mentioned are the coordinates of a bounding box that defines a closed area within a 5km range of a given set of coordinates.

A bounding box is a rectangular area that encloses a set of points or coordinates. In this case, the bounding box encloses the coordinates that are within a 5km range of the given coordinates. The minimum and maximum latitude and longitude values that were calculated earlier define the boundaries of this bounding box.

By combining the minimum and maximum latitude and longitude values, you get a rectangular area that encloses all the coordinates that are within a 5km range of the given coordinates. Any coordinate that lies within this rectangular area can be considered to be within a 5km range of the given coordinates.

This information can be useful in various applications, such as mapping, geolocation-based services, or location-based searches. For example, if you want to search for all the restaurants within a 5km range of a given location, you can use the bounding box coordinates to filter out the restaurants that are outside the 5km range.

Can you tell me more with example for bounding box calculations?

Sure, here’s an example of how you can calculate the bounding box coordinates for a given set of coordinates within a 5km range.

Let’s assume that the given coordinates are:

Latitude: 37.7749 Longitude: -122.4194

To calculate the bounding box coordinates:

  1. Calculate the minimum and maximum latitude:
  • min latitude = 37.7749 – (5 / 111.2) = 37.7692
  • max latitude = 37.7749 + (5 / 111.2) = 37.7807
  1. Calculate the minimum and maximum longitude:
  • min longitude = -122.4194 – (5 / (111.2 * cos(37.7749))) = -122.4257
  • max longitude = -122.4194 + (5 / (111.2 * cos(37.7749))) = -122.4131

So, the bounding box coordinates would be:

min latitude: 37.7692 min longitude: -122.4257 max latitude: 37.7807 max longitude: -122.4131

This means that any coordinate that lies within the rectangular area defined by these bounding box coordinates would be considered to be within a 5km range of the given coordinates (37.7749, -122.4194).

Well hope you understand from the given formulation and examples how can create a boundingbox for the range we need to search in for against our given co-ordinates, lets deep in further how we can implement and take this up with our Javascript Skills!

Nice, how I we can use this in Javascript?

Here’s an example of how you can calculate the bounding box coordinates for a given set of coordinates within a 5km range using JavaScript:

function getBoundingBox(lat, lng, distance) {
  const RADIUS_OF_EARTH_KM = 6371;
  const latRadian = lat * (Math.PI / 180);
  const degLatKm = RADIUS_OF_EARTH_KM * Math.cos(latRadian);
  const degLonKm = RADIUS_OF_EARTH_KM;
  const latDegree = distance / degLatKm;
  const lngDegree = distance / degLonKm;

  return {
    minLat: lat - latDegree,
    minLng: lng - lngDegree,
    maxLat: lat + latDegree,
    maxLng: lng + lngDegree
  };
}

const coordinates = { lat: 37.7749, lng: -122.4194 };
const boundingBox = getBoundingBox(coordinates.lat, coordinates.lng, 5);

console.log(boundingBox);

In this example, the getBoundingBox function takes the latitude, longitude, and distance as input parameters. The distance is the radius of the bounding box and is specified in kilometers. The function first converts the latitude and longitude to radians and calculates the number of kilometers per degree of latitude and longitude. The minimum and maximum latitude and longitude values are then calculated using these values and the given distance. Finally, the bounding box coordinates are returned as an object.

Nice, How to I use the bounding box with real test case example?

Here’s an example of how you could use the bounding box coordinates with a real-world test case. Let’s say you have a list of restaurants and their coordinates, and you want to search for all the restaurants within a 5km range of a given location.

const restaurants = [
  { name: "Restaurant A", lat: 37.7820, lng: -122.4464 },
  { name: "Restaurant B", lat: 37.7696, lng: -122.4138 },
  { name: "Restaurant C", lat: 37.7816, lng: -122.4140 },
  { name: "Restaurant D", lat: 37.7711, lng: -122.4336 },
  { name: "Restaurant E", lat: 37.7634, lng: -122.4359 },
];

const searchLocation = { lat: 37.7749, lng: -122.4194 };
const searchRadius = 5;
const boundingBox = getBoundingBox(searchLocation.lat, searchLocation.lng, searchRadius);

const filteredRestaurants = restaurants.filter(restaurant => {
  return (
    restaurant.lat >= boundingBox.minLat &&
    restaurant.lat <= boundingBox.maxLat &&
    restaurant.lng >= boundingBox.minLng &&
    restaurant.lng <= boundingBox.maxLng
  );
});

console.log(filteredRestaurants);

In this example, the restaurants array contains the list of restaurants and their coordinates. The searchLocation object contains the location for which you want to search the restaurants. The searchRadius specifies the radius of the search in kilometers.

The boundingBox is calculated using the getBoundingBox function, as shown in the previous example. The filteredRestaurants array is then created by filtering the restaurants array based on whether their coordinates fall within the bounding box or not. Finally, the filtered restaurants are logged to the console.

Hope this give us nice insight for the questions we have and need to develop as we develop advance things.

Source: Some AI Interaction Channels

Happy Learning!

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
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!