<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Coding Beauty Tutorials on Medium]]></title>
        <description><![CDATA[Stories by Coding Beauty Tutorials on Medium]]></description>
        <link>https://medium.com/@codingbeautytutorials?source=rss-4e218897e959------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GKAJc1kw7N9BT2NqQzjHbg.png</url>
            <title>Stories by Coding Beauty Tutorials on Medium</title>
            <link>https://medium.com/@codingbeautytutorials?source=rss-4e218897e959------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:35:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codingbeautytutorials/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fix “Cannot read property ‘map’ of undefined” in React]]></title>
            <link>https://medium.com/@codingbeautytutorials/react-cannot-read-property-map-of-undefined-da7d70a387a6?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/da7d70a387a6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 11:37:57 GMT</pubDate>
            <atom:updated>2023-12-07T11:39:12.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82nUfABxYpPqaYPnmRpcwA.png" /></figure><p>Are you currently experiencing the “Cannot read property ‘map’ of undefined” error in your React app?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/0*wkYUgQ0Hy_xK6hMl.png" /></figure><p>This error happens when you call the map() method on a variable that was meant to be an array, but is actually undefined. The variable could be a property or state variable.</p><p>For example:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { fetchBooks } from &#39;./books&#39;;<br><br>function App() {<br>  // ❌ `books` is `undefined`<br>  const [books, setBooks] = useState(undefined);<br>  <br>  useEffect(() =&gt; {<br>    (async () =&gt; {<br>      setBooks(await fetchBooks());<br>    })();<br>  }, []);<br>  return (<br>    &lt;div&gt;<br>      {books.map((book) =&gt; (<br>        &lt;div key={book.id}&gt;<br>          &lt;h2&gt;Title: {book.title}&lt;/h2&gt;<br>          &lt;p&gt;Author: {book.author}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>We’ll use this example to learn some easy ways to quickly fix this error in React.</p><h3>Fix: Use optional chaining operator (?.)</h3><p>To fix the “Cannot use property ‘map’ of undefined” error in React.js, use the optional chaining operator (?.) to access the map() method:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { fetchBooks } from &#39;./books&#39;;<br><br>function App() {<br>  const [books, setBooks] = useState(undefined);<br>  <br>  useEffect(() =&gt; {<br>    (async () =&gt; {<br>      setBooks(await fetchBooks());<br>    })();<br>  }, []);<br>  return (<br>    &lt;div&gt;<br>      {/* ✅ Fix with optional chaining (?.) */}<br>      {books?.map((book) =&gt; (<br>        &lt;div key={book.id}&gt;<br>          &lt;h2&gt;Title: {book.title}&lt;/h2&gt;<br>          &lt;p&gt;Author: {book.author}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>The optional chaining operator lets us safely access a property on a value that may be undefined or null. If it is, the operator will return undefined immediately and prevent the property access or method call.</p><pre>const auth = undefined;<br><br>console.log(auth); // undefined<br><br>// ✅ No error<br>console.log(auth?.user?.name); // undefined</pre><h3>Fix: Use AND operator (&amp;&amp;)</h3><p>You can also use the &amp;&amp; operator to check if the value is undefined before access it in the JSX:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { fetchBooks } from &#39;./books&#39;;<br><br>function App() {<br>  const [books, setBooks] = useState(undefined);<br>  <br>  useEffect(() =&gt; {<br>    (async () =&gt; {<br>      setBooks(await fetchBooks());<br>    })();<br>  }, []);<br>  return (<br>    &lt;div&gt;<br>      {/* ✅ Fix with AND operator (&amp;&amp;) */}<br>      {books &amp;&amp;<br>        books.map((book) =&gt; (<br>          &lt;div key={book.id}&gt;<br>            &lt;h2&gt;Title: {book.title}&lt;/h2&gt;<br>            &lt;p&gt;Author: {book.author}&lt;/p&gt;<br>          &lt;/div&gt;<br>        ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Here’s what a chain of &amp;&amp; does: it returns the right-most variable if all the variables are truthy. Otherwise, it returns the left-most falsy variable:</p><pre>console.log(undefined &amp;&amp; 0 &amp;&amp; []); // undefined<br><br>console.log(10 &amp;&amp; null &amp;&amp; &#39;coding&#39;); // null<br><br>console.log(10 &amp;&amp; [5, 7] &amp;&amp; &#39;coding&#39;); // coding</pre><p><strong>Note:</strong> These are the falsy values in JavaScript: undefined, null, 0, false, &#39;&#39; (empty string), and NaN. Every other value is truthy.</p><h3>Fix: Initialize state variable to empty array</h3><p>The applies when the array value is a state variable like in our example.</p><p>We set the state to an empty array ([]) at the point where it&#39;s created, so it never becomes undefined, preventing the &quot;Cannot read property &#39;map&#39; of undefined&quot; error in the React app.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { fetchBooks } from &#39;./books&#39;;<br><br>function App() {<br>  // ✅ `books` starts out as an array, not `undefined`<br>  const [books, setBooks] = useState([]);<br>  <br>  useEffect(() =&gt; {<br>    (async () =&gt; {<br>      setBooks(await fetchBooks());<br>    })();<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {books.map((book) =&gt; (<br>        &lt;div key={book.id}&gt;<br>          &lt;h2&gt;Title: {book.title}&lt;/h2&gt;<br>          &lt;p&gt;Author: {book.author}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h3>Fix: Create a loading state when fetching data</h3><p>Apart from initializing the state to an empty array you can also display a loading indicator when performing network request, or some other time-consuming operation:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { fetchBooks } from &#39;./books&#39;;<br><br>function App() {<br>  const [books, setBooks] = useState(undefined);<br>  const [loading, setLoading] = useState(true);<br><br>  useEffect(() =&gt; {<br>    (async () =&gt; {<br>      setBooks(await fetchBooks());<br>    })();<br>    // ✅ Lists books with .map() after loading completes<br>    setLoading(false);<br>  }, []);<br><br>  let listEl;<br>  if (loading) {<br>    listEl = &lt;div&gt;Loading...&lt;/div&gt;;<br>  } else {<br>    listEl = (<br>      &lt;div&gt;<br>        {books.map((book) =&gt; (<br>          &lt;div key={book.id}&gt;<br>            &lt;h2&gt;Title: {book.title}&lt;/h2&gt;<br>            &lt;p&gt;Author: {book.author}&lt;/p&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    );<br>  }<br>  return &lt;div&gt;{listEl}&lt;/div&gt;<br>}<br><br>export default App;</pre><p>Most web user interfaces have at least three states — loading, error, and success state, and we could be better off representing all three of them:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { fetchBooks } from &#39;./books&#39;;<br><br>// TypeScript<br>// type UIState = &#39;loading&#39; | &#39;error&#39; | &#39;success&#39;;<br>function App() {<br>  const [books, setBooks] = useState(undefined);<br>  const [state, setState] = useState(&#39;loading&#39;);<br>  <br>  // TypeScript<br>  // const [state, setState] = useState&lt;UIState&gt;(&#39;loading&#39;);<br>  useEffect(() =&gt; {<br>    try {<br>      (async () =&gt; {<br>        setBooks(await fetchBooks());<br>        setState(&#39;success&#39;);<br>      })();<br>      // ✅ Lists books with .map() after loading completes<br>    } catch (err) {<br>      setState(&#39;error&#39;);<br>    }<br>  }, []);<br><br>  const listViewMap = {<br>    loading: &lt;div&gt;Loading...&lt;/div&gt;,<br>    error: &lt;div&gt;An error occured, try again later.&lt;/div&gt;,<br>    success: (<br>      &lt;div&gt;<br>        {books.map((book) =&gt; (<br>          &lt;div key={book.id}&gt;<br>            &lt;h2&gt;Title: {book.title}&lt;/h2&gt;<br>            &lt;p&gt;Author: {book.author}&lt;/p&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    ),<br>  };<br>  const listEl = listViewMap[state];<br>  return &lt;div&gt;{listEl}&lt;/div&gt;;<br>}<br><br>export default App;</pre><h3>Fix: Check the value assigned to the array</h3><p>Maybe you initialized the array properly and did everything else right, but you set it to undefined at some point in the code.</p><p>If the array is to be filled with API data, are you sure you’re making the network request properly.</p><p>For example, if our fetchBooks() function was defined like below, it will cause a &quot;Cannot read property &#39;map&#39; of undefined&quot; error when there&#39;s a network error on the user&#39;s device.</p><pre>export async function fetchBooks() {<br>  const res = fetch(&#39;https://api.example/books&#39;, {<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      Accept: &#39;application/json&#39;,<br>    },<br>  });<br>  // ❌ Will return `undefined` if status code is not 200<br>  return res.status === 200 ? (await res).json() : undefined;<br>}</pre><p>Make sure you handle all the edge cases in your app.</p><h3>Fix: Check your variable names</h3><p>Sometimes the error happens due to a error in your variable names.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { fetchBooks } from &#39;./books&#39;;<br><br>function App() {<br>  const [books, setBooks] = useState([]);<br><br>  useEffect(() =&gt; {<br>    (async () =&gt; {<br>      setBooks(await fetchBooks());<br>    })();<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {books.map((books) =&gt; (<br>        &lt;div key={book.id}&gt;<br>          &lt;h2&gt;Title: {book.title}&lt;/h2&gt;<br>          &lt;p&gt;Author: {book.author}&lt;/p&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Here we mistakenly create a books variable in the map() callback but we use book identifier in the JSX, which is what we actually intended. The causes the unfortunate error, aside from the fact that it shadows the outer books state variable.</p><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><p><em>Originally published at </em><a href="https://www.codingbeautydev.com/blog/react-cannot-read-property-map-of-undefined?utm_source=medium&amp;utm_medium=social&amp;utm_campaign=blog"><em>codingbeautydev.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da7d70a387a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get URL query string params in Next.js]]></title>
            <link>https://medium.com/@codingbeautytutorials/nextjs-get-url-query-params-00be4d6bcc2f?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/00be4d6bcc2f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 22:29:57 GMT</pubDate>
            <atom:updated>2023-11-26T22:33:42.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to get URL query string parameters in Next.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cR_LEgaZPQzFNLEDyi2_Ug.png" /></figure><p>Query parameters are used to pass data from the URL to the web server or browser. They are essential for customizing user experiences, filtering data, and tracking user actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Form25bWm-Q4O01K.png" /></figure><p>Let’s learn how to easily get the query string parameters from a URL in a Next.js app.</p><h3>Get URL query params in Next.js App Router client component</h3><p>To get the URL query string parameters in the Next.js app directory, use the useSearchParams() hook from next/navigation.</p><pre>// app/amazing-url/page.tsx<br><br>&#39;use client&#39;;<br><br>import { useSearchParams } from &#39;next/navigation&#39;;<br><br>export default function Home() {<br>  const searchParams = useSearchParams();<br>  const query = searchParams.get(&#39;q&#39;);<br><br>  return (<br>    &lt;&gt;<br>      Welcome to Coding Beauty<br>      &lt;br /&gt;<br>      &lt;br /&gt;<br>      Your query: &lt;b&gt;{query}&lt;/b&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>We need ‘use client’ to use useSearchParams()</h3><p>Notice the &#39;use client&#39; statement at the top.</p><p>It’s there because all components in the new app directory are server components by default, so we can&#39;t use any client-side specific functionality like hooks and animations.</p><p>We’ll get an error if we try to do anything interactive with useSearchParams or other hooks like useEffect, because it&#39;s a server environment.</p><h3>Get URL query params in Next.js Pages Router component</h3><p>To get the URL query string parameters in pages directory component, use the query property of the useRouter() hook, which comes from the next/router module:</p><pre>// pages/coding-tips.tsx<br><br>import Head from &#39;next/head&#39;;<br>import { useRouter } from &#39;next/router&#39;;<br><br>export default function Home() {<br>  const router = useRouter();<br>  const greeting = router.query.greeting;<br><br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Coding Tips | Coding Beauty&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Generated by create next app&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.icon&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        &lt;h2&gt;{greeting}&lt;/h2&gt;<br>        &lt;p&gt;Appreciate the beauty of coding&lt;/p&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Get URL query params in Next.js middleware</h3><p>To get the URL query string parameters in Next.js App or Pages Router middleware, use the request.nextUrl.searchParams property:</p><pre>// middleware.ts<br><br>import { NextResponse } from &#39;next/server&#39;;<br>import { NextRequest } from &#39;next/server&#39;;<br><br>export function middleware(request: NextRequest) {<br>  const continueUrl =<br>    request.nextUrl.searchParams.get(&#39;continue&#39;)!;<br>  return NextResponse.redirect(continueUrl);<br>}</pre><h3>Get URL query params in Next.js server component</h3><p>To get the URL query params in a server component, se the URL as a header in middleware, then parse this URL in the server component to get the query string and parameters:</p><pre>// middleware.ts<br><br>import { NextResponse } from &#39;next/server&#39;;<br>import { NextRequest } from &#39;next/server&#39;;<br><br>export function middleware(request: NextRequest) {<br>  const reqHeaders = new Headers(request.headers);<br>  // toLowerCase() to avoid 404 due to Next.js case-sensitivity<br><br>  const url = request.url.toLowerCase();<br>  reqHeaders.set(&#39;x-url&#39;, url);<br>  return NextResponse.next({<br>    request: {<br>      headers: reqHeaders,<br>    },<br>  });<br>}</pre><pre>// app/search/page.tsx<br><br>import { headers } from &#39;next/headers&#39;;<br><br>export default function Page() {<br>  const headerList = headers();<br>  const url = headerList.get(&#39;x-url&#39;)!;<br>  const query = new URL(url).searchParams.get(&#39;q&#39;);<br><br>  return (<br>    &lt;&gt;<br>      &lt;h2&gt;Welcome to Coding Beauty.&lt;/h2&gt;<br>      &lt;p&gt;Your query: {query}&lt;/p&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Get URL query params in getServerSideProps()</h3><p>To get the URL query string params in the Pages Router getServerSideProps() function, use the context.query property:</p><pre>// pages/random-lyrics.tsx<br><br>export async function getServerSideProps(context) {<br>  const { songId } = context.query;<br>  const res = await fetch(`https://api.example.com/lyrics?songId=${songId}`);<br>  const lyrics = await res.json();<br>  return {<br>    props: {<br>      lyrics,<br>    },<br>  };<br>}<br><br>export default function LyricsPage({ lyrics }) {<br>  const { song, content } = lyrics;<br>  return (<br>    &lt;div&gt;<br>      {song} lyrics&lt;div&gt;{content}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Get URL query params in Next.js Pages Router API</h3><p>To get the URL query string parameters in an API in the pages directory, use the request.query property.</p><pre>// pages/api/stock-prices.tsx<br><br>import type { NextApiRequest, NextApiResponse } from &#39;next&#39;;<br><br>export default async function handler(<br>  req: NextApiRequest,<br>  res: NextApiResponse<br>) {<br>  const { name } = req.query;<br>  const stockRes = await fetch(`api.example.com/stock-prices?name=${name}`);<br>  const stockData = await stockRes.json();<br>  res.status(200).json({ stockData });<br>}</pre><h3>Get URL query params in Next.js App Router API</h3><p>To get the URL query string params in an API in the Next.js 13 app directory, use the request.nextUrl.searchParams property:</p><pre>// app/api/forecast/route.ts<br><br>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br><br>const data = {<br>  &#39;new-york&#39;: { summary: &#39;sunny&#39; }<br>  // ...<br>}<br><br>export async function GET(req: NextRequest) {<br>  const location = req.nextUrl.searchParams.get(&#39;location&#39;);<br>  const weatherData = data[location];<br>  return NextResponse.json({ weatherData });<br>}</pre><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><p><em>Originally published at </em><a href="https://www.codingbeautydev.com/blog/nextjs-get-url-query-params?utm_source=medium&amp;utm_medium=social&amp;utm_campaign=blog"><em>codingbeautydev.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00be4d6bcc2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 quick fixes for the “Cannot not find module” error in Node.js]]></title>
            <link>https://medium.com/@codingbeautytutorials/nodejs-cannot-find-module-7be18c361280?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be18c361280</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 21:30:37 GMT</pubDate>
            <atom:updated>2023-11-24T00:46:35.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Solved] Cannot find module in Node.js (MODULE_NOT_FOUND)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3kP3x9KHWotw9WIQudq2g.png" /></figure><p>Are you experiencing the “Cannot find module” or MODULE_NOT_FOUND error in your Node.js project?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cZ-y5e-F86Z8tg4v.png" /></figure><p>This error happens when your IDE can’t detect the presence of a particular NPM package. Let’s see how easy it is to fix.</p><h3>1. Ensure NPM package installed</h3><p>To fix the “Cannot find module” error in Node.js, make sure the NPM package is installed and present in your package.json file.</p><p>You can install a package from NPM with the npm i command, for example:</p><pre># NPM <br>npm i nextjs-current-url<br><br># Yarn<br>yarn add nextjs-current-url<br><br># PNPM<br>pnpm add nextjs-current-url</pre><p>After installation, the package will included under the dependencies field in package.json</p><pre>{<br>  ...<br>  &quot;dependencies&quot;: {<br>    ...<br>    &quot;nextjs-current-url&quot;: &quot;^1.0.1&quot;<br>    ...<br>  }<br>  ...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7iJSeyqI_sVJUCVV.png" /></figure><p>You can also install the package as a development dependency, which indicates that the package is only used for development, and won’t be needed by the app itself. Packages like nodemon and <a href="https://www.codingbeautydev.com/blog/ts-node-unknown-file-extension-ts">ts-node</a> fit this category:</p><pre># NPM<br>npm i -D ts-node<br><br># Yarn<br>yarn add -D ts-node<br><br># PNPM<br>pnpm add -D ts-node</pre><p>It will be part of devDependencies in package.json after installation:</p><pre>{<br>  ...<br>  &quot;devDependencies&quot;: {<br>    ...<br>    &quot;ts-node&quot;: &quot;^10.9.1&quot;<br>    ...<br>  }<br>}</pre><h3>2. Install package again</h3><p>To fix the MODULE_NOT_FOUND error in Node.js, trying installing the package in your project once again, even if you did so earlier:</p><pre># NPM<br>npm i -D try-catch-fn<br><br># Yarn<br>yarn add try-catch-fn<br><br># NPM<br>yarn add try-catch-fn</pre><h3>3. Reinstall all packages</h3><p>Try removing the NPM packages installed in your project and reinstalling them again, to fix the “Cannot find module” error.</p><p>You can do this with the following command sequence:</p><pre># NPM<br>rm package-lock.json<br>rm node_modules -r<br>npm cache clear<br>npm install<br><br># Yarn<br>rm yarn.lock<br>rm node_modules -r<br>yarn cache clean<br>yarn install<br>s<br># PNPM<br>rm pnpm-lock.yaml<br>rm node_modules -r<br>pnpm store prune<br>pnpm install</pre><p>npm cache clear helps to rid the package manager cache of any corrupted module files.</p><h3>4. TypeScript: Install type definitions</h3><p>The MODULE_NOT_FOUND error will occur when you import a package that doesn’t have any detected type definitions into a TypeScript file.</p><p>If it’s a core Node.js module like http or fs, you may need to add &quot;node&quot; to compilerOptions.types in your tsconfig.json file:</p><pre>{<br>  // ...<br>  &quot;compilerOptions&quot;: {<br>    // ...<br>    &quot;types&quot;: [<br>      &quot;node&quot;<br>    ]<br>    // ...<br>  },<br>  // ...<br>}</pre><p>If it’s a third-party module, installing the type definitions from NPM should help. For example:</p><pre>npm i @types/express</pre><h3>5. Ensure package.json main file exists</h3><p>You may encounter the “Cannot find module” error in Node.js if the main field of your package.json file doesn&#39;t exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I506i01RyNjodVjF.png" /></figure><h3>6. npm link package</h3><p>You can also try the npm link command on the package to fix the MODULE_NOT_FOUND error, for example:</p><pre>npm link create-react-app<br><br>npm link webpack</pre><p>npm link is a command that connects a globally installed package with a local project using a symbolic link.</p><p>It enables working on a package locally without publishing it to the npm registry or reinstalling it for every change. Executing npm link in the package directory establishes a symbolic link in the global node_modules directory, directing to the local package.</p><p>Afterwards, npm link &lt;package-name&gt; can be used in the project to link the global package with your local project.</p><h3>7. Ensure correct NODE_PATH</h3><p>In older Node.js versions, you may be able to fix the “Cannot find module” error by setting the NODE_PATH environment variable to correct node_modules installation folder.</p><p>NODE_PATH is a string of absolute paths separated by colons used by Node.js to locate modules when they can&#39;t be found elsewhere.</p><p>It was initially created to enable the loading of modules from different paths when there was no defined module resolution algorithm.</p><p>And it’s still supported, but it’s not as important anymore since the we’ve established a convention for finding dependent modules in Node.js community.</p><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><p><em>Originally published at </em><a href="https://www.codingbeautydev.com/blog/nodejs-cannot-find-module?utm_source=medium&amp;utm_medium=social&amp;utm_campaign=blog"><em>codingbeautydev.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be18c361280" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to easily get the current URL in Next.js]]></title>
            <link>https://medium.com/@codingbeautytutorials/nextjs-get-current-url-e4e1373333b2?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4e1373333b2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 20:58:37 GMT</pubDate>
            <atom:updated>2023-11-12T20:58:37.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vGQZipmLTuY6WnuN.png" /></figure><p>We use the current URL in a web app to track user activity, maintain history, or modify displayed elements based on route. So, let’s see how to quickly get the current URL in a Next.js app.</p><h3>Get current URL in Next.js Pages Router component</h3><p>To get the current URL in a Next.js component, use the useUrl hook from the nextjs-current-url package:</p><p>With pages directory:</p><pre>// src/pages/index.tsx<br><br>import { useUrl } from &#39;nextjs-current-url&#39;;<br>import Head from &#39;next/head&#39;;<br><br>export default function Home() {<br>  const { href: currentUrl, pathname } = useUrl() ?? {};<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Next.js - Coding Beauty&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Next.js Tutorials by Coding Beauty&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.png&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        Welcome to Coding Beauty 😄<br>        &lt;br /&gt;<br>        &lt;br /&gt;<br>        URL: &lt;b&gt;{currentUrl}&lt;/b&gt;<br>        &lt;br /&gt;<br>        pathname: &lt;b&gt;{pathname}&lt;/b&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iB72zLjKCUWgBM7V.png" /></figure><p>useUrl() returns a <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL">URL</a> object that gives us more info on the current URL.</p><h3>Get current URL with useState and window.location.href</h3><p>We can also get the current URL in a client component using useState and window.location.href.</p><pre>// src/pages/index.tsx<br><br>import Head from &#39;next/head&#39;;<br>import { useRouter } from &#39;next/router&#39;;<br>import { useEffect } from &#39;react&#39;;<br><br>export default function Home() {<br>  const [currentUrl, setCurrentUrl] = useState&lt;string | null&gt;(null);<br>  const { pathname } = useRouter();<br>  useEffect(() =&gt; {<br>    setCurrentUrl(window.location.href);<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Next.js - Coding Beauty&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Next.js Tutorials by Coding Beauty&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        Welcome to Coding Beauty 😄<br>        &lt;br /&gt;<br>        &lt;br /&gt;<br>        URL: &lt;b&gt;{currentUrl}&lt;/b&gt;<br>        &lt;br /&gt;<br>        pathname: &lt;b&gt;{pathname}&lt;/b&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>The window.location.href property returns a string containing the entire page URL, and we use the useState and useEffect hooks to create and set state for storing the current URL.</p><h3>window.location property</h3><p>window.location has other properties that tell you more about the URL. Like:</p><ul><li>pathname: the path of the URL after the domain name and any optional port number. Query and fragment identifier not included.</li><li>protocol: URL&#39;s protocol scheme, like https: or mailto:. Doesn&#39;t include the //.</li><li>hostname: the URL&#39;s domain name without the port number.</li></ul><p>Here’s an example where we use some of these properties:</p><pre>// src/pages/index.tsx<br><br>import { getUrl } from &#39;@/lib/utils/get-url&#39;;<br>import { NextPageContext } from &#39;next&#39;;<br>import Head from &#39;next/head&#39;;<br>import { useEffect, useState } from &#39;react&#39;;<br><br>export function getServerSideProps(context: NextPageContext) {<br>  return {<br>    props: {<br>      currentUrl: getUrl({ req: context.req! })?.href,<br>    },<br>  };<br>}<br><br>export default function Home() {<br>  const [myLocation, setMyLocation] = useState&lt;Location | null&gt;(null);<br>  useEffect(() =&gt; {<br>    setMyLocation(window.location);<br>  });<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Next.js - Coding Beauty&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Next.js Tutorials by Coding Beauty&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.png&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        You are currently accessing &lt;b&gt;{myLocation?.href}&lt;/b&gt; 😃<br>        &lt;br /&gt;<br>        Pathname: &lt;b&gt;{myLocation?.pathname}&lt;/b&gt;<br>        &lt;br /&gt;<br>        Protocol: &lt;b&gt;{myLocation?.protocol}&lt;/b&gt;<br>        &lt;br /&gt;<br>        Hostname: &lt;b&gt;{myLocation?.hostname}&lt;/b&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2i-ym9h4T0VOqf3V.png" /></figure><h3>We need useEffect to get the current URL</h3><p>Pages render on both the server and client in Next.js, so when the server renders the page, there’s no window object available.</p><p>So you’ll get a “window is not defined” error if you try to use window before hydration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9qItM8vtm-gDgFnX.png" /></figure><p>That’s why we use useEffect - to wait till mounting/hydration is done.</p><p>What’s hydration?</p><p>Hydration is when a server-generated web page gets extra client-side features added by the user’s web browser. Features like event listeners, client-side routing, etc.</p><h3>Get current URL in Next.js App Router component</h3><p>To get the current URL in a Next.js app router component, we can also use the useUrl hook from the nextjs-current-url library.</p><pre>// src/app/page.tsx<br><br>&#39;use client&#39;;<br>import React from &#39;react&#39;;<br>import { useUrl } from &#39;nextjs-current-url&#39;;<br>import { Metadata } from &#39;next&#39;;<br><br>export const metadata: Metadata = {<br>  title: &#39;Next.js - Coding Beauty&#39;,<br>  description: &#39;Next.js Tutorials by Coding Beauty&#39;,<br>};<br><br>export default function Page() {<br>  const { pathname, href } = useUrl() ?? {};<br>  return (<br>    &lt;main&gt;<br>      Welcome to Coding Beauty<br>      &lt;br /&gt;<br>      &lt;br /&gt;<br>      URL: &lt;b&gt;{href}&lt;/b&gt;<br>      &lt;br /&gt;<br>      route: &lt;b&gt;{pathname}&lt;/b&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*07P9Iks0f409qlJZ.png" /></figure><h3>Next.js App Router: We need &#39;use client&#39;</h3><p>Notice the &#39;use client&#39; statement at the top.</p><p>It’s there because all components in the new app directory are server components by default, so we can&#39;t use any client-side specific APIS.</p><p>We’ll get an error if we try to do anything interactive with useEffect or other hooks like useUrl, because it&#39;s a server environment.</p><h3>Get current URL in Next.js getServerSideProps</h3><p>To get the current URL in getServerSideProps of a Next.js page, use the getUrl function from the nextjs-current-url library.</p><pre>// src/pages/amazing-url.tsx<br><br>import { NextPageContext } from &#39;next&#39;;<br>import Head from &#39;next/head&#39;;<br>import { getUrl } from &#39;nextjs-current-url/server&#39;;<br><br>export function getServerSideProps(context: NextPageContext) {<br>  const url = getUrl({ req: context.req });<br>  return {<br>    props: {<br>      url: url.href,<br>    },<br>  };<br>}<br><br>export default function Home({ url }: { url: string }) {<br>  const urlObj = new URL(url);<br>  const { pathname } = urlObj;<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Next.js - Coding Beauty&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Generated by create next app&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.png&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        Welcome to Coding Beauty 😃<br>        &lt;br /&gt;<br>        &lt;br /&gt;<br>        URL: &lt;b&gt;{url}&lt;/b&gt;<br>        &lt;br /&gt;<br>        Route: &lt;b&gt;{pathname}&lt;/b&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P9ehrMVg8hfNW8nl.png" /></figure><p>Let’s check out some more properties of URL:</p><pre>// src/pages/amazing-url.tsx<br><br>import { NextPageContext } from &#39;next&#39;;<br>import Head from &#39;next/head&#39;;<br>import { getUrl } from &#39;nextjs-current-url/server&#39;;<br><br>export function getServerSideProps(context: NextPageContext) {<br>  const url = getUrl({ req: context.req });<br>  return {<br>    props: {<br>      url: url.href,<br>    },<br>  };<br>}<br><br>export default function Home({ url }: { url: string }) {<br>  const urlObj = new URL(url);<br>  const { pathname, href, protocol, hostname, search, hash } = urlObj;<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Next.js - Coding Beauty&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Generated by create next app&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.png&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        Welcome to Coding Beauty 😃<br>        &lt;br /&gt;<br>        &lt;br /&gt;<br>        URL: &lt;b&gt;{href}&lt;/b&gt;<br>        &lt;br /&gt;<br>        Pathname: &lt;b&gt;{pathname}&lt;/b&gt;<br>        &lt;br /&gt;<br>        Protocol: &lt;b&gt;{protocol}&lt;/b&gt;<br>        &lt;br /&gt;<br>        Hostname: &lt;b&gt;{hostname}&lt;/b&gt;<br>        &lt;br /&gt;<br>        Search: &lt;b&gt;{search}&lt;/b&gt;<br>        &lt;br /&gt;<br>        Hash: &lt;b&gt;{hash}&lt;/b&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Here’s what these properties do:</p><ul><li>href: the complete URL, including the protocol, hostname, port number, path, query parameters, and fragment identifier.</li><li>protocol: URL&#39;s protocol scheme, like https: or mailto:. Doesn&#39;t include the //.</li><li>hostname: the URL&#39;s domain name without the port number.</li><li>pathname: the URL&#39;s path and filename without the query and fragment identifier.</li><li>search: the URL&#39;s query parameters. Includes the ?</li><li>hash: the fragment identifier, the part after the #.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ehqy-tpsM7RcRgpN.png" /></figure><p><strong>Note:</strong> As you can see it’s not possible to get the hash/fragment in getServerSideProps because the browser never sends the part after the # to the server. That&#39;s why there&#39;s no hash here. We&#39;d have to get the current URL in the client-side to access the fragment identifier.</p><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4e1373333b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to easily get the current route in Next.js]]></title>
            <link>https://medium.com/@codingbeautytutorials/nextjs-get-current-route-d0b45c038858?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0b45c038858</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Sat, 11 Nov 2023 20:46:37 GMT</pubDate>
            <atom:updated>2023-11-11T20:47:21.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mCov_LYKF2AhUDYZ.png" /></figure><p>Getting the current route in a web application is important for managing user sessions, handling authentication, and dynamically displaying UI elements.</p><p>Let’s how see how easy it is to get the current route or pathname in our Next.js app.</p><h3>Get current route in Next.js Pages Router component</h3><p>We can get the current route in a Next.js component with the useRouter hook:</p><pre>src/pages/blog.tsx<br><br>import Head from &#39;next/head&#39;;<br>import { useRouter } from &#39;next/router&#39;;<br><br>export default function Page() {<br>  const { pathname } = useRouter();<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Next.js - Coding Beauty&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Next.js Tutorials by Coding Beauty&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        Welcome to Coding Beauty<br>        &lt;br /&gt;<br>        &lt;br /&gt;<br>        Pathname: &lt;b&gt;{pathname}&lt;/b&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CIAW3Kuc0iqHW_dB.png" /></figure><h3>Get current route in Next.js App Router component</h3><p>To get the current route in a Next.js app router component, use the usePathname hook from next/navigation:</p><pre>// src/app/amazing-url/page.tsx<br><br>&#39;use client&#39;;<br>import React from &#39;react&#39;;<br>import { Metadata } from &#39;next&#39;;<br>import { usePathname } from &#39;next/navigation&#39;;<br><br>export const metadata: Metadata = {<br>  title: &#39;Next.js - Coding Beauty&#39;,<br>  description: &#39;Next.js Tutorials by Coding Beauty&#39;,<br>};<br><br>export default function Page() {<br>  const pathname = usePathname();<br>  return (<br>    &lt;main&gt;<br>      Welcome to Coding Beauty 😄<br>      &lt;br /&gt;<br>      &lt;br /&gt;<br>      Route: &lt;b&gt;{pathname}&lt;/b&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yiMHrwHXvCKfBoYm.png" /></figure><h3>We need &#39;use client&#39; in Next.js 13 App Router</h3><p>Notice the &#39;use client&#39; statement at the top.</p><p>It’s there because all components in the new app directory are server components by default, which means we can&#39;t access client-side specific APIs.</p><p>We’ll get an error if we try to do anything interactive with useEffect or other hooks, as it&#39;s a server environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aFu2b3YD7iCoQLme.png" /></figure><h3>Get current route in Next.js getServerSideProps</h3><p>To get the current route in getServerSideProps, use req.url from the context argument.</p><pre>// src/pages/amazing-url.tsx<br><br>import { NextPageContext } from &#39;next&#39;;<br>import Head from &#39;next/head&#39;;<br><br>export function getServerSideProps(context: NextPageContext) {<br>  const route = context.req!.url;<br>  console.log(`The route is: ${route}`);<br>  return {<br>    props: {<br>      route,<br>    },<br>  };<br>}<br><br>export default function Page({ route }: { route: string }) {<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Next.js - Coding Beauty&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content=&quot;Generated by create next app&quot; /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.png&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        Welcome to Coding Beauty 😃<br>        &lt;br /&gt;<br>        Route: &lt;b&gt;{route}&lt;/b&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*uFQQOBR_c1lKwexg.png" /></figure><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0b45c038858" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to easily fix the “Cannot read property ‘classList’ of null” error in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/javascript-cannot-read-property-classlist-of-undefined-7de2429c8f92?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de2429c8f92</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 06:16:55 GMT</pubDate>
            <atom:updated>2024-08-05T08:12:46.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Easily Fix the “Cannot Read Property ‘classList’ of Null” Error in JavaScript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiR6mB8hhd2BFKKOvA5k5w.png" /></figure><p>The “Cannot read property ‘classList’ of null” error happens in JavaScript when you try to access the classList property on an element that isn&#39;t in the HTML DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xryapK9YHbj6EH8I.png" /></figure><p>Let’s look at various ways to quickly fix this error.</p><h3>Fix: Ensure correct selector</h3><p>To fix the “Cannot read property ‘classList’ of null” error in JavaScript, ensure the correct selector accesses an existing HTML element.</p><pre>&lt;div&gt;Welcome to Coding Beauty&lt;/div&gt;<br>&lt;button class=&quot;btn-1&quot;&gt;Be amazing&lt;/button&gt;</pre><p>Check for any mistakes in the selector symbols in the script. Check for any mistakes in the ID or class name in the HTML tag. Maybe you forgot to set that id or class attribute at all?</p><pre>// forgot the &#39;.&#39; symbol used for class selectors <br>const button = document.querySelector(&#39;btn-1&#39;);<br><br>console.log(button); // 👉️ undefined<br>// ❌ Uncaught TypeError: Cannot read properties of undefined (reading &#39;classList&#39;)<br>button.classList.add(&#39;active&#39;);</pre><blockquote><em>💡</em> <strong>Useful one-liners that are commonly needed in web development:</strong></blockquote><p><a href="https://differ.blog/p/10-useful-javascript-one-liners-i-use-at-work-8ffcf4">10 Useful JavaScript One-Liners to Improve Your Efficiency</a></p><blockquote><em>👉</em> To read more such acrticles, <a href="https://differ.blog/"><strong>sign up for free on Differ</strong></a>.</blockquote><h3>Fix: Ensure DOM load before .classList access</h3><p>The “Cannot read property ‘classList’ of undefined” error also occurs when you try to access .classList on an element that the browser hasn&#39;t added to the DOM yet.</p><p>Maybe because your &lt;script&gt; is in the &lt;head&gt; tag and executes before the element&#39;s parsing:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Coding Beauty Tutorial&lt;/title&gt;<br>    &lt;!-- ❌ Script is run before button is declared --&gt;<br>    &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;element&quot;&gt;<br>      console.log(&#39;Easy answers to your coding questions and more...&#39;);<br>    &lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The script tag is placed in the &lt;head&gt; tag above where the div is declared, so index.js can&#39;t access the div.</p><pre>// index.js<br><br>const element = document.querySelector(&#39;.element&#39;);<br>console.log(element); // 👉️ undefined<br><br>// ❌ Uncaught TypeError: Cannot read properties of undefined (reading &#39;classList&#39;)<br>element.classList.add(&#39;highlight&#39;);</pre><h3>Solution: Move script to bottom</h3><p>To fix the error in this case, move the script tag to the bottom of the body, after all the HTML elements have been declared.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Coding Beauty Tutorial&lt;/title&gt;<br>    <br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;element&quot;&gt;<br>      console.log(&#39;Easy answers to your coding questions and more...&#39;);<br>    &lt;/div&gt;<br>    <br>    &lt;!-- ❌ Script is run after element is added to the DOM --&gt;<br>    &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now index.js will have access to the div and all the other HTML elements, because the browser would have rendered them by the time the script runs:</p><pre>// index.js<br><br>const element = document.querySelector(&#39;.element&#39;);<br>console.log(element); // 👉️ undefined<br><br>// ✅ Works as expected<br>element.classList.add(&#39;highlight&#39;);</pre><h3>Solution: Access .classList in DOMContentLoaded event listener</h3><p>Another way to fix the “cannot read property ‘addEventListener’ of null” error is to add a DOMContentLoaded event listener to the document and access the element in this listener.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Coding Beauty Tutorial&lt;/title&gt;<br>    &lt;!-- Script placed above accessed element --&gt;<br>    &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;element&quot;&gt;<br>      console.log(&#39;Coding is more than a means to an end...&#39;);<br>    &lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The DOMContentLoaded event fires when the browser fully parses the HTML, whether or not external resources like images and stylesheets have loaded.</p><p>So regardless of where we place the script, the code in the listener only runs after every element is active in the DOM.</p><pre>// index.js<br><br>const element = document.querySelector(&#39;.element&#39;);<br>console.log(element); // 👉️ undefined<br><br>// ✅ Works as expected<br>element.classList.add(&#39;highlight&#39;);</pre><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><p><em>Originally published at </em><a href="https://www.codingbeautydev.com/blog/javascript-cannot-read-property-classlist-of-null?utm_source=medium&amp;utm_medium=social&amp;utm_campaign=blog"><em>codingbeautydev.com</em></a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de2429c8f92" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/javascript-cannot-read-property-classlist-of-undefined-7de2429c8f92">How to easily fix the “Cannot read property ‘classList’ of null” error in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Easily Set the Page Title and Meta Description of a Page in Next.js]]></title>
            <link>https://medium.com/@codingbeautytutorials/nextjs-set-page-title-meta-description-24f729dadb85?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f729dadb85</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 13:47:14 GMT</pubDate>
            <atom:updated>2023-10-26T13:47:14.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhhHVhiWEvKc2tw1uTCEUg.png" /></figure><p>Setting the page title and meta description helps improve search engine visibility, increase click-through rates, and provide concise summaries of webpage content.</p><p>Let’s learn how to easily set the page title and meta description in a Next.js project.</p><h3>Set static page title and meta description in Next.js App Router</h3><p>To set page title and meta description statically in Next.js 13’s app directory, create a Metadata object in a page.tsx file and export it:</p><pre>// src/app/page.tsx<br><br>import React from &#39;react&#39;;<br>import { Metadata } from &#39;next&#39;;<br><br>export const metadata: Metadata = {<br>  title: &#39;Coding Beauty&#39;,<br>  description:<br>    &#39;codingbeautydev.com: Coding - the art, the science, and the passion.&#39;,<br>};<br><br>export default function Page() {<br>  return (<br>    &lt;main&gt;<br>      &lt;h1&gt;Welcome to Coding Beauty&lt;/h1&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>The tab will have this title, and the page will have a meta tag containing this description:</p><p>We can also do this in a layout.tsx to make every page using this layout have this title and meta description by default - if the page doesn&#39;t have its own.</p><pre>// src/app/layout.tsx<br><br>import { Metadata } from &#39;next&#39;;<br>import &#39;@/styles/globals.css&#39;;<br><br>export const metadata: Metadata = {<br>  title: &#39;Coding Beauty&#39;,<br>  description: &#39;The official Coding Beauty home page.&#39;,<br>  icons: {<br>    icon: &#39;/favicon.png&#39;,<br>  },<br>};<br><br>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode;<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;{children}&lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><h3>Set title and meta description dynamically in Next.js App Router</h3><p>You can use the generateMetadata() function to set the page title and meta description using dynamic information we don&#39;t know beforehand, like data from an API.</p><pre>export function generateMetadata({ params }: Props): Promise&lt;Metadata&gt; {<br>  // fetch data with `params`<br><br>  // return a `Metadata` object<br>  return {<br>    title: post.name,<br>    description: post.description,<br>  }<br>}</pre><p>Let’s look at a full example, where we fetch API data for a post in our hypothetical social media app, and we use generateMetadata() to set the page title and meta description for the page based on what we get from the endpoint <a href="https://www.codingbeautydev.com/blog/nextjs-get-current-url">URL</a>.</p><pre>// src/pages/posts/[id]/page.tsx<br><br>import { Metadata } from &#39;next&#39;;<br><br>type Props = {<br>  params: { id: string };<br>};<br><br>export async function generateMetadata({<br>  params,<br>}: Props): Promise&lt;Metadata&gt; {<br>  const id = params.id;<br>  const url = `https://api.mysocialapp.com/posts/${id}`;<br>  const post = await fetch(url).then((res) =&gt; res.json());<br>  return {<br>    title: post.title,<br>    description: post.description,<br>  };<br>}<br><br>export default async function Page({ params }: Props) {<br>  const { id } = params;<br>  const url = `https://api.mysocialapp.com/posts/${id}`;<br>  // fetch again!<br>  // But don&#39;t worry, Next.js caches the `fetch()` calls<br>  const post = await fetch(url).then((res) =&gt; res.json());<br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;{post.title}&lt;/h1&gt;<br>      &lt;div&gt;{post.content}&lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>We fetch data from the same endpoint twice, one for the title and meta description, and another to display the title and other information to the actual users on the page.</p><p>Next.js caches the results of the fetch in generateMetadata() for use in Page to prevent multiple requests and avoid performance hits.</p><p>If you export a Metadata object and also have generateMetadata() function, Next.js will use generateMetadata()&#39;s return value.</p><h3>Set page title and meta description in Next.js Pages Router (&lt;= 12)</h3><p>To set the page title and meta description in the Next.js pages directory, create a Head component, and place meta and title tags in it, like you would in vanilla HTML:</p><pre>// pages/index.tsx<br><br>import Head from &#39;next/head&#39;;<br><br>export default function Home() {<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Coding Beauty&lt;/title&gt;<br>        &lt;meta<br>          name=&quot;description&quot;<br>          content=&quot;A brand all about coding passion and success&quot;<br>        /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.png&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        &lt;h1&gt;Welcome to Coding Beauty&lt;/h1&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>We can also set the page title and meta description in your _app.tsx or _app.jsx file to make each page without a title or description use this as a default.</p><pre>// pages/_app.tsx<br><br>import &#39;@/styles/globals.css&#39;;<br>import type { AppProps } from &#39;next/app&#39;;<br>import Head from &#39;next/head&#39;;<br><br>export default function App({ Component, pageProps }: AppProps) {<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        &lt;title&gt;Coding Beauty&lt;/title&gt;<br>        &lt;meta<br>          name=&quot;description&quot;<br>          content=&quot;A page on the Coding Beauty website&quot;<br>        /&gt;<br>      &lt;/Head&gt;<br>      &lt;Component {...pageProps} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Set page title and meta description dynamically in Next.js Pages Router (&lt;= 12)</h3><p>You can also set the page title and meta description in the pages directory based on some data not known ahead of time.</p><p>For instance, to set the meta information based on API data, you’ll fetch the data in getServerSideProps and display it in the title and meta tags that are in the Head tag.</p><pre>// pages/[id].tsx<br><br>import { GetServerSideProps } from &#39;next&#39;;<br>import Head from &#39;next/head&#39;;<br><br>export const getServerSideProps: GetServerSideProps = async (context) =&gt; {<br>  const { params } = context;<br>  const { id } = params!;<br>  const result = await fetch(`api.mystore.com/books/${id}`);<br>  const { title, description, details } = await result.json();<br>  return {<br>    props: {<br>      title,<br>      description,<br>      details,<br>    },<br>  };<br>};<br><br>export default function Home(props: any) {<br>  const { title, description, details } = props;<br>  return (<br>    &lt;&gt;<br>      &lt;Head&gt;<br>        {/* 👇 set page title and meta description dynamically */}<br>        &lt;title&gt;{title}&lt;/title&gt;<br>        &lt;meta name=&quot;description&quot; content={description} /&gt;<br>        &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>        &lt;link rel=&quot;icon&quot; href=&quot;/favicon.png&quot; /&gt;<br>      &lt;/Head&gt;<br>      &lt;main&gt;<br>        &lt;h1&gt;{title}&lt;/h1&gt;<br>        &lt;p&gt;{details}&lt;/p&gt;<br>      &lt;/main&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><p><em>Originally published at </em><a href="https://www.codingbeautydev.com/blog/nextjs-set-page-title-meta-description?utm_source=medium&amp;utm_medium=social&amp;utm_campaign=blog"><em>codingbeautydev.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f729dadb85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy Ways to Add or Toggle a Class on the Body Element in JavaScript]]></title>
            <link>https://medium.com/@codingbeautytutorials/javascript-add-toggle-class-body-d748b42ec707?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/d748b42ec707</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 01:14:17 GMT</pubDate>
            <atom:updated>2023-10-26T01:14:17.591Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Easily Add or Toggle a Class on the Body Element in JavaScript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woLPX-47R7T1yZQ5bIW8dA.png" /></figure><p>Adding a class to the &lt;body&gt; tag can be useful for applying global styles or targeting specific elements within the body for styling or functionality.</p><p>This article will teach us how to easily add or toggle a class on the HTML body element using JavaScript.</p><p>To add a class to the HTML body element in JavaScript on page load, call the classList.add() method on it, i.e., document.body.classList.add(element).</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Coding Beauty Tutorial&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body class=&quot;dev coding&quot;&gt;<br>    &lt;div&gt;This is a div element.&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><pre>// Script<br><br>document.body.classList.add(&#39;class-3&#39;);</pre><p>The body property is the HTMLElement object that represents the body tag in the markup.</p><p>The classList property is a DOMTokenList object that represents the list of classes an element has.</p><p>The add() method of the classList property takes a list of classes and adds them to an element.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Coding Beauty Tutorial&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body class=&quot;dev coding beauty&quot;&gt;<br>    &lt;div&gt;This is a div element.&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>You can pass multiple arguments to add() to add more than one class to the body. For example, we can add both beauty and magic to the body in <a href="https://www.codingbeautydev.com/blog/javascript-one-liners">single statement</a>.</p><pre>document.body.classList.add(&#39;beauty&#39;, &#39;magic&#39;);</pre><p>To produce this HTML markup:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Coding Beauty Tutorial&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body class=&quot;dev coding beauty magic&quot;&gt;<br>    &lt;div&gt;This is a div element.&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>If you add class that already exists on the HTML body, add() ignores the class instead of throwing an exception.</p><h3>Add class to body tag in &lt;head&gt; tag</h3><p>To add a class to the body element in the &lt;head&gt; tag using JavaScript, use the DOMContentLoaded event and the document.body.classList.add() method.</p><p>For example:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Coding Beauty Tutorial&lt;/title&gt;<br>    &lt;script&gt;<br>      document.addEventListener(&#39;DOMContentLoaded&#39;, () =&gt; {<br>        document.body.classList.add(&#39;beauty&#39;, &#39;magic&#39;);<br>      });<br>    &lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body class=&quot;dev coding&quot;&gt;<br>    &lt;div&gt;This is a div element.&lt;/div&gt;<br>    &lt;script src=&quot;index&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The DOMContentLoaded event runs when the HTML is completely parse and the DOM has loaded.</p><p>The &lt;script&gt; loads and the JavaScript runs before the browser renders the HTML, so without DOMContentLoaded, document.body will be null in the &lt;script&gt;, causing the &quot;Cannot read property &#39;classList&#39; of undefined&quot; JavaScript error.</p><h3>Add class to body tag on click</h3><p>If you’d like to add a class to the body tag when the user clicks an element, set a click listener on element and call document.body.classList.add() in this listener.</p><p>For example:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Coding Beauty Tutorial&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body class=&quot;dev coding&quot;&gt;<br>    &lt;div&gt;So you can code&lt;/div&gt;<br>    &lt;button class=&quot;amazify&quot;&gt;Be amazing&lt;/button&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><pre>const button = document.getElementById(&#39;amazify&#39;);<br><br>button.addEventListener(&#39;click&#39;, () =&gt; {<br>  document.body.classList.add(&#39;amazify&#39;);<br>});</pre><h3>Toggle class on body element</h3><p>Toggling a class on the body element in JavaScript simplifies code implementation by handling the addition and <a href="https://www.codingbeautydev.com/blog/javascript-remove-class-from-body">removal of the class</a> in a single line of code.</p><p>And this single line of code is a call to the body’s classList.toggle() method:</p><pre>document.body.classList.toggle(&#39;incredible&#39;);</pre><p>As you would expect, the <a href="https://www.codingbeautydev.com/blog/javascript-remove-class-from-body">class is removed from the body</a> when it’s already there and added when it isn’t.</p><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><p><em>Originally published at </em><a href="https://www.codingbeautydev.com/blog/javascript-add-class-to-body?utm_source=medium&amp;utm_medium=social&amp;utm_campaign=blog"><em>codingbeautydev.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d748b42ec707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to easily get the intersection of two sets in JavaScript]]></title>
            <link>https://medium.com/@codingbeautytutorials/javascript-get-intersection-of-two-sets-cc46d791680e?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc46d791680e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 12:06:48 GMT</pubDate>
            <atom:updated>2023-10-09T12:06:48.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTCn4OrJOdjVQz6rimlfaQ.png" /></figure><p>To get the intersection of two Sets in JavaScript, combine the filter() and has() array methods:</p><pre>const set1 = new Set([1, 2, 3, 4, 5]);<br>const set2 = new Set([4, 5, 6, 7, 8]);<br><br>const intersection = new Set([...set1].filter(x =&gt; set2.has(x)));<br><br>console.log(intersection); // Set {4, 5}</pre><p>The <a href="https://codingbeautydev.com/blog/javascript-filter-duplicate-objects-from-array/">Array </a><a href="https://codingbeautydev.com/blog/javascript-filter-duplicate-objects-from-array/">filter()</a> method tests each element in an array against a condition specified by a callback function and creates a new array filled with elements that pass the test. It doesn’t modify the original array.</p><pre>const arr = [1, 2, 3, 4];<br><br>const filtered = arr.filter((num) =&gt; num &gt; 2);<br>console.log(filtered); // [ 3, 4 ]</pre><p>The spread syntax (...) converts the Set to an array:</p><pre>const set1 = new Set([1, 2, 3, 4, 5]);<br><br>const arrayFromSet = [...set1];<br><br>console.log(arrayFromSet); // [1, 2, 3, 4, 5]</pre><p>We can also do this with the Array from() method, which converts Sets and other iterables into arrays:</p><pre>const set1 = new Set([1, 2, 3, 4, 5]);<br><br>const arrayFromSet = Array.from(set1);<br><br>console.log(arrayFromSet); // [1, 2, 3, 4, 5]</pre><p>And the Set has() method tells us whether or not the Set contains a particular element.</p><pre>const set = new Set([&#39;coding&#39;, &#39;beauty&#39;, &#39;dev&#39;]);<br><br>const hasElegance = set.has(&#39;elegance&#39;);<br>const hasBeauty = set.has(&#39;beauty&#39;);<br><br>console.log(hasElegance); // false<br>console.log(hasBeauty); // true</pre><h3>Get intersection of two sets with Array forEach() method</h3><p>Alternatively, we can use the Array forEach() method to get the intersection of two Sets in JavaScript.</p><pre>const set1 = new Set([1, 2, 3, 4, 5]);<br>const set2 = new Set([4, 5, 6, 7, 8]);<br>const intersection = new Set();<br><br>set1.forEach(value =&gt; {<br>  if (set2.has(value)) {<br>    intersection.add(value);<br>  }<br>});<br><br>console.log(intersection); // Set {4, 5}</pre><p>The Set forEach loops through an array and calls a specified function on each element.</p><pre>const fruits = new Set([&#39;apple&#39;, &#39;orange&#39;, &#39;banana&#39;]);<br><br>fruits.forEach((fruit) =&gt; {<br>  console.log(fruit.toUpperCase());<br>});<br><br>// Output 👇<br>// APPLE<br>// ORANGE<br>// BANANA</pre><p>The Set add() method adds a new element to a Set:</p><pre>const set = new Set([1, 2, 3]);<br><br>console.log(set);  // Set(3) { 1, 2, 3 }<br><br>set.add(10);<br><br>console.log(set);  // Set(4) { 1, 2, 3, 10 }</pre><h3>Get intersection of two Sets with for..of loop</h3><p>Anywhere you see the forEach(), you can use the for..of loop in its place:</p><pre>const set1 = new Set([1, 2, 3, 4, 5]);<br>const set2 = new Set([4, 5, 6, 7, 8]);<br>const intersection = new Set();<br><br>for (const value of set1) {<br>  if (set2.has(value)) {<br>    intersection.add(value);<br>  }<br>}<br><br>console.log(intersection); // Set {4, 5}</pre><h3>Get intersection of two Sets with reduce() method</h3><p>You can also use the reduce() method to get the intersection of two Set objects in JavaScript:</p><pre>const set1 = new Set([1, 2, 3, 4, 5]);<br>const set2 = new Set([4, 5, 6, 7, 8]);<br><br>const intersection = [...set1].reduce((acc, value) =&gt; {<br>  if (set2.has(value)) {<br>    acc.add(value);<br>  }<br>  return acc;<br>}, new Set());<br><br>console.log(intersection); // Set {4, 5}</pre><p>The reduce() method calls a function on each element of an array to accumulate a resulting value:</p><pre>const nums = [1, 2, 3, 4, 5];<br><br>const sum = nums.reduce((acc, num) =&gt; acc + num, 0);<br><br>const product = nums.reduce((acc, num) =&gt; acc * num, 1);<br><br>console.log(sum);  // 15<br><br>console.log(product);  // 120</pre><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><p><em>Originally published at </em><a href="https://cbdev.link/ba12ad"><em>codingbeautydev.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc46d791680e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to quickly fix the “Cannot read property ‘then’ of undefined” error in JavaScript]]></title>
            <link>https://medium.com/@codingbeautytutorials/javascript-cannot-read-property-then-of-undefined-35a216d1954f?source=rss-4e218897e959------2</link>
            <guid isPermaLink="false">https://medium.com/p/35a216d1954f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Coding Beauty Tutorials]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 06:01:36 GMT</pubDate>
            <atom:updated>2023-10-06T06:01:36.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaKXtWjJ7PoNMXrlAPMwTQ@2x.png" /></figure><p>The “Cannot read property ‘then’ of undefined” error occurs in JavaScript when you call try then() on a value - typically a function&#39;s return value - but this value is undefined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*I23rkq9HQIsGQh-P.png" /><figcaption>The “Cannot read property ‘then’ of undefined” error occurring in VS Code.</figcaption></figure><p>This could happen for one of the following reasons:</p><ol><li>Not returning the Promise in the function with return.</li><li>Not returning a value in an async function.</li><li>Not chaining Promises properly.</li></ol><p>To fix it, ensure the function returns actually returns a Promise.</p><p>Now let’s look at some specific cases of the error and learn how to fix it in a few easy steps.</p><h3>Fix: Promise not returned</h3><p>The “Cannot read property ‘then’ of undefined” happens when you forget to use the return keyword return the Promise from the function.</p><pre>function fetchData(apiUrl) {<br>  // 👇 `return` keyword missing<br>  fetch(apiUrl).then((response) =&gt; {<br>    return response.json();<br>  });<br><br>  // ❌ Cannot read property &#39;then&#39; of undefined<br>  fetchData(&#39;/api/data&#39;)<br>    .then((data) =&gt; console.log(data))<br>}</pre><p>To fix it, simply return the Promise with return:</p><pre>function fetchData(apiUrl) {<br>  // we return the Promise<br>  return fetch(apiUrl).then((response) =&gt; {<br>    return response.json();<br>  });<br><br>  // ✅ Runs successfully<br>  fetchData(&#39;/api/data&#39;)<br>    .then((data) =&gt; console.log(data))<br>}</pre><h3>Fix: Asynchronous function doesn’t return a value</h3><p>The “Cannot read property ‘then’ of undefined” error happens in JavaScript when an async function doesn&#39;t return a value, for example, due to an oversight on our part when writing conditional control flow.</p><pre>async function getUserData(userId) {<br>  if (userId) {<br>    const response = await fetch(`/api/users/${userId}`);<br>    return response.json();<br>  }<br>  // 😕 No return if userId is absent<br><br>  // ❌ Cannot read property &#39;then&#39; of undefined if userId is absent<br>  getUserData().then(data =&gt; console.log(data));<br>}</pre><p>To fix it, check all flow paths and make sure the async function always returns a value.</p><pre>async function getUserData(userId) {<br>  if (userId) {<br>    const response = await fetch(`/api/users/${userId}`);<br>    return response.json();<br>  }<br><br>  // 👍 Return a resolved Promise even if userId is absent<br>  return Promise.resolve(null);<br>}<br><br>// ✅ Now, we can safely use &#39;then&#39;<br>getUserData().then(data =&gt; console.log(data));</pre><h3>Fix: Promise is not properly chained</h3><p>The “Cannot read property ‘then’ of undefined” error occurs in JavaScript when you don’t chain the Promises properly:</p><pre>function fetchAndParseUser(apiUrl) {<br>  fetch(apiUrl)<br>    .then((response) =&gt; {<br>      console.log(response);<br>      // 😕 Forgot to return the &#39;json&#39; Promise<br>    });<br>}<br><br>// ❌ Error: Cannot read property &#39;then&#39; of undefined<br>fetchAndParseUser(&#39;/api/user&#39;)<br>  .then(data =&gt; console.log(data))</pre><p>To fix it in this case, make sure that each then in the chain returns a Promise if we want to continue the chain.</p><pre>function fetchAndParseUser(apiUrl) {<br>  // 👇 Here, we return the &#39;json&#39; Promise<br>  return fetch(apiUrl)<br>    .then((response) =&gt; {<br>      console.log(response);<br>      return response.json();  // 👍 Return the Promise here<br>    });<br>}<br><br>// ✅ Now, we can safely use &#39;then&#39;<br>fetchAndParseUser(&#39;/api/user&#39;)<br>  .then(data =&gt; console.log(data))</pre><h3>Every Crazy Thing JavaScript Does</h3><p>Just when you thought you knew all the quirks.<br>Avoid painful bugs and save valuable time with <strong>Every Crazy Thing JavaScript Does, </strong>a captivating guide to the subtle caveats and lesser-known parts of JavaScript.</p><p><strong>Get a free copy </strong><a href="https://cbdev.link/d3c4eb"><strong>here</strong></a><strong> today.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*YS5Oub8REWy8vnOEqBnsyQ.png" /></figure><p><em>Originally published at </em><a href="https://cbdev.link/c2d5bb"><em>codingbeautydev.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35a216d1954f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>