<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: indrasisdatta</title>
    <description>The latest articles on DEV Community by indrasisdatta (@indrasisdatta).</description>
    <link>https://dev.to/indrasisdatta</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1116733%2Ff8c4a281-740b-46c9-9fa1-253a2eb90aae.jpg</url>
      <title>DEV Community: indrasisdatta</title>
      <link>https://dev.to/indrasisdatta</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/indrasisdatta"/>
    <language>en</language>
    <item>
      <title>Using Middleware to Format Express API Response</title>
      <dc:creator>indrasisdatta</dc:creator>
      <pubDate>Mon, 20 Nov 2023 09:25:23 +0000</pubDate>
      <link>https://dev.to/indrasisdatta/using-middleware-to-format-express-api-response-1k6a</link>
      <guid>https://dev.to/indrasisdatta/using-middleware-to-format-express-api-response-1k6a</guid>
      <description>&lt;p&gt;Middleware in Express allows you to customize and enhance the request-response cycle. One powerful application of middleware is to format the response before it is sent back to the client. &lt;/p&gt;

&lt;p&gt;We'll explore how to create a middleware function to expose only specific user fields and restrict fields like password, _id etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Route&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Router } from "express";
const router = Router();
router.get("/profile", getUserProfile, UserResponse);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Controller&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We are fetching user details based on request POST param &lt;code&gt;userId&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;user&lt;/code&gt; returns Mongoose User but we don't want to expose all fields in our response. Therefore, we can assign the response json to &lt;code&gt;res.locals&lt;/code&gt; so that it can be passed on to the middleware.&lt;br&gt;
Ref: &lt;a href="https://expressjs.com/en/5x/api.html#res.locals"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* User profile details */
export const getUserProfile = async (
  req: Request,
  res: Response,
  next: NextFunction
) =&amp;gt; {
  try {
    const { userId } = req;
    if (!userId ) {
      return res.status(400).json({
        status: 0,
        data: null,
        error: "User not found",
      });
    }
    const user = User.findById(userId);
    // Store data here, which can be accessed in middleware
    res.locals.apiResponse = {
      status: 1,
      data: user,
    };
    next(); // this is important so that it's forwarded to UserResponse middleware
  } catch (error) {
    res.status(500).json({ status: API_STATUS.ERROR, error });
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Creating the middleware&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { NextFunction, Request, Response } from "express";

export const UserResponse = (
  req: Request,
  res: Response,
  Next: NextFunction
) =&amp;gt; {
  try {
    if (res.locals?.apiResponse) {
      if (
        res.locals.apiResponse?.status == 1 &amp;amp;&amp;amp;
        typeof res.locals.apiResponse?.data === "object" &amp;amp;&amp;amp;
        res.locals.apiResponse?.data.constructor.modelName === "User"
      ) {
        const tempUser = res.locals.apiResponse?.data.toObject();
        /* Delete all private fields so that only necessary fields are exposed */
        delete tempUser._id;
        delete tempUser.createdAt;
        delete tempUser.updatedAt;
        delete tempUser.password;
        delete tempUser?.__v;
        return res.status(200).json({
          status: res.locals.apiResponse?.status,
          data: tempUser,
        });
      }
    }
    return res.status(200).json(res.locals);
  } catch (error) {
    res.status(500).json({ status: 0, error });
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>node</category>
      <category>middlewares</category>
      <category>express</category>
    </item>
    <item>
      <title>Vanilla JS Debounce using API example</title>
      <dc:creator>indrasisdatta</dc:creator>
      <pubDate>Tue, 11 Jul 2023 10:14:42 +0000</pubDate>
      <link>https://dev.to/indrasisdatta/vanilla-js-debounce-using-api-example-372k</link>
      <guid>https://dev.to/indrasisdatta/vanilla-js-debounce-using-api-example-372k</guid>
      <description>&lt;h2&gt;
  
  
  Understanding Debounce:
&lt;/h2&gt;

&lt;p&gt;Debouncing refers to a technique used to optimize the execution of a function by delaying its invocation until a certain amount of time has passed. The below example demonstrates the use of debouncing in a products search functionality.&lt;/p&gt;

&lt;p&gt;In this search products example, it's supposed to return API data based on search input. To reduce the no. of API calls, &lt;code&gt;searchProducts()&lt;/code&gt; is called after a slight delay.&lt;/p&gt;

&lt;h2&gt;
  
  
  HTML:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- Search product --&amp;gt;
&amp;lt;input id="product" /&amp;gt;

&amp;lt;!-- Show search results --&amp;gt;
&amp;lt;div id="search-result"&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  JS:
&lt;/h2&gt;

&lt;p&gt;The delayWrapper function is a higher-order function that creates a debounced version of the provided function func. It sets up a timer to delay the execution of func until the specified timeout period has passed.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const delayWrapper = (func, timeout) =&amp;gt; {
    let timer;
  return (...args) =&amp;gt; {
    clearTimeout(timer);
    timer = setTimeout(() =&amp;gt; {
      func(...args)
    }, timeout);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;delayedCall&lt;/code&gt;variable is assigned the debounced version of the &lt;code&gt;searchProducts&lt;/code&gt;function, created using &lt;code&gt;delayWrapper&lt;/code&gt;. It has a delay of 500 milliseconds (0.5 seconds).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const delayedCall = delayWrapper(searchProducts, 500);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;searchProducts&lt;/code&gt; function uses the provided search query q to fetch data from an API endpoint using fetch. The retrieved data is stored in products variable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const searchProducts = async (q) =&amp;gt; {
  let products = [];
  try {
    console.log(`Search param: ${q}`)
    const response = await fetch(`https://dummyjson.com/products/search?q=${q}`);
    const data = await response.json();
    products = data.products;
  } catch (e) {
    console.error('Error found: ', e);
  }
  renderProducts(products);  
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;renderProducts&lt;/code&gt;function takes an array of products as a parameter and generates HTML based on the products. If there are products, it creates an unordered list ul with list items li representing each product's title.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const renderProducts = (products) =&amp;gt; {
    let searchHtml = '';
    if (products.length &amp;gt; 0) {
        searchHtml = '&amp;lt;ul&amp;gt;';
        products.map(prod =&amp;gt; {
            searchHtml += `&amp;lt;li&amp;gt;${prod.title}&amp;lt;/li&amp;gt;`;
        })
        searchHtml += '&amp;lt;/ul&amp;gt;';
    }
    console.log('Search html', searchHtml)
    document.getElementById('search-result').innerHTML = searchHtml;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;iframe src="https://jsfiddle.net/ry7o2pLn/2//embedded//dark" width="100%" height="600"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Full JS Code:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('product').addEventListener('keyup', (e) =&amp;gt; {
    delayedCall(e.target.value);
})


const searchProducts = async (q) =&amp;gt; {
    let products = [];
    try {
        console.log(`Search param: ${q}`)
        const response = await fetch(`https://dummyjson.com/products/search?q=${q}`);
        const data = await response.json();
        console.log('API data', data)
        products = data.products;
    } catch (e) {
        console.error('Error found: ', e);
    }
    renderProducts(products);
}

const delayWrapper = (func, timeout) =&amp;gt; {
    let timer;
    return (...args) =&amp;gt; {
        clearTimeout(timer);
        timer = setTimeout(() =&amp;gt; {
            func(...args)
        }, timeout);
    }
}

const delayedCall = delayWrapper(searchProducts, 1500);

const renderProducts = (products) =&amp;gt; {
    let searchHtml = '';
    if (products.length &amp;gt; 0) {
        searchHtml = '&amp;lt;ul&amp;gt;';
        products.map(prod =&amp;gt; {
            searchHtml += `&amp;lt;li&amp;gt;${prod.title}&amp;lt;/li&amp;gt;`;
        })
        searchHtml += '&amp;lt;/ul&amp;gt;';
    }
    console.log('Search html', searchHtml)
    document.getElementById('search-result').innerHTML = searchHtml;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>React JS - Scenario-based questions</title>
      <dc:creator>indrasisdatta</dc:creator>
      <pubDate>Mon, 10 Jul 2023 09:14:22 +0000</pubDate>
      <link>https://dev.to/indrasisdatta/react-js-scenario-based-questions-cg7</link>
      <guid>https://dev.to/indrasisdatta/react-js-scenario-based-questions-cg7</guid>
      <description>&lt;p&gt;In the last quarter of 2022, I appeared for multiple interviews and made a habit of noting down all questions and brushing up the ones which I couldn't answer. &lt;br&gt;
&lt;em&gt;**Note: most are from React but 2-3 are general web development concepts.&lt;/em&gt;*&lt;/p&gt;

&lt;p&gt;I decided to make a list of the scenario based/practical questions which I came across from my personal experience. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Why does &lt;strong&gt;Cross-Origin Resource Sharing (CORS)&lt;/strong&gt; error occur? How to handle it from frontend as well as backend?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How to &lt;strong&gt;globally attach a JWT token&lt;/strong&gt; to every request header? Without modifying each and every API function?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When trying to &lt;strong&gt;close browser&lt;/strong&gt;, how can we show a custom popup &lt;strong&gt;"Are you sure? You have unsaved changes."&lt;/strong&gt;?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How can we &lt;strong&gt;prevent&lt;/strong&gt; a function from being &lt;strong&gt;called too many times&lt;/strong&gt; in a row? Eg. search input change firing API call  &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If same state value is updated, does component &lt;strong&gt;re-render&lt;/strong&gt;? Does &lt;strong&gt;child components&lt;/strong&gt; re-render? Assuming there's no memo code.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In Redux, can we have &lt;strong&gt;multiple states or a single state&lt;/strong&gt;?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Does React.memo do &lt;strong&gt;deep **or **shallow **comparison? How to add **custom comparison&lt;/strong&gt; function? &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How do you optimize a webpage that's using &lt;strong&gt;multiple images&lt;/strong&gt;? Eg. list shows 250 countries with flag images&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How to manage &lt;strong&gt;env based&lt;/strong&gt; versions of React project? Eg. different API endpoints, builds for Dev, QA, Prod.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;How to run &lt;strong&gt;concurrent API calls&lt;/strong&gt;? Eg. on button click, 5 independent API calls are made. When all 5 API responses are received, only then show success message to user.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Component &lt;strong&gt; *&lt;em&gt;has a loop which renders multiple *&lt;/em&gt;&lt;/strong&gt; components. Clicking each child component &lt;strong&gt;&lt;/strong&gt; makes a function call to parent component's &lt;code&gt;display()&lt;/code&gt; function. How can we optimize performance?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using &lt;code&gt;useState&lt;/code&gt;, how can we initialize value from a function using expensive calculation? &lt;br&gt;
Eg.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function expensive() {
 // expensive calculation logic
 return result;
} 
const [myState, setMyState] = useState( // use expensive function's return value here )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
  </channel>
</rss>
