<?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: Rajiv Chaulagain</title>
    <description>The latest articles on DEV Community by Rajiv Chaulagain (@rajivchaulagain).</description>
    <link>https://dev.to/rajivchaulagain</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%2F922327%2F157e51e2-3991-4b2b-b076-a01a05f63310.jpeg</url>
      <title>DEV Community: Rajiv Chaulagain</title>
      <link>https://dev.to/rajivchaulagain</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rajivchaulagain"/>
    <language>en</language>
    <item>
      <title>Best Practices for Writing Clean and Maintainable JavaScript Code</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Tue, 22 Oct 2024 08:18:53 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/best-practices-for-writing-clean-and-maintainable-javascript-code-124p</link>
      <guid>https://dev.to/rajivchaulagain/best-practices-for-writing-clean-and-maintainable-javascript-code-124p</guid>
      <description>&lt;p&gt;&lt;strong&gt;1. Meaningful Variable and Function Names:&lt;/strong&gt;&lt;br&gt;
Tip: Use descriptive names that clearly indicate the purpose of the variable or function.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Copy code
// Bad
const x = calculate(5);

// Good
const totalPrice = calculatePrice(5);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Descriptive Comments:&lt;/strong&gt;&lt;br&gt;
Tip: Write concise but meaningful comments to explain complex logic or intent. Comments should clarify why something is done, not what is being done (which should be clear from the code itself).&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bad
// Loops through the array
array.forEach(item =&amp;gt; doSomething(item));

// Good
// Process each item to filter out non-active users
array.forEach(item =&amp;gt; filterActiveUsers(item));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Single Responsibility Principle:&lt;/strong&gt;&lt;br&gt;
Tip: Ensure that functions and methods perform one specific task, making them reusable and easy to debug.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bad
function handleUserLoginAndDisplayUserProfile() { /* multiple tasks */ }

// Good
function handleUserLogin() { /* one task */ }
function displayUserProfile() { /* one task */ }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Consistent Formatting and Style:&lt;/strong&gt;&lt;br&gt;
Tip: Use consistent code formatting (indentation, spaces) and follow style guidelines (camelCase for variables, PascalCase for classes, etc.).&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;js
Copy code
// Bad
function fetchData(){return 'data'}

// Good
function fetchData() {
  return 'data';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Avoid Magic Numbers and Strings:&lt;/strong&gt;&lt;br&gt;
Tip: Use named constants instead of hardcoding numbers or strings, which makes your code more readable and maintainable.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bad
const discount = total * 0.1;

// Good
const DISCOUNT_RATE = 0.1;
const discount = total * DISCOUNT_RATE;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Write Modular Code:&lt;/strong&gt;&lt;br&gt;
Tip: Break down your code into smaller, reusable modules or functions. This increases reusability and maintainability.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bad
function processOrder(order) { /* many tasks */ }

// Good
function validateOrder(order) { /* one task */ }
function calculateTotal(order) { /* one task */ }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;7. Use Meaningful Error Handling:&lt;/strong&gt;&lt;br&gt;
Tip: Catch and handle errors properly, giving meaningful feedback to developers or users.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bad
try {
  processOrder(order);
} catch (e) {
  console.log(e);
}

// Good
try {
  processOrder(order);
} catch (error) {
  console.error(`Failed to process order: ${error.message}`);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;8. DRY Principle (Don't Repeat Yourself):&lt;/strong&gt;&lt;br&gt;
Tip: Avoid duplicating code by refactoring common logic into functions or modules.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bad
const userAge = getUserAge();
const userName = getUserName();

// Good
function getUserDetails() {
  return {
    age: getUserAge(),
    name: getUserName(),
  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>When to use if-else, switch-case, or functions like Array.prototype.includes() or Array.prototype.find()</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Fri, 27 Sep 2024 09:07:11 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/when-to-use-if-else-switch-case-or-functions-like-arrayprototypeincludes-or-arrayprototypefind-1nip</link>
      <guid>https://dev.to/rajivchaulagain/when-to-use-if-else-switch-case-or-functions-like-arrayprototypeincludes-or-arrayprototypefind-1nip</guid>
      <description>&lt;p&gt;In JavaScript, choosing between if-else, switch-case, or functions like Array.prototype.includes() or Array.prototype.find() depends on the specific use case, readability, performance, and the type of conditions you are handling. Below is a comparison of these constructs, along with suggestions for when to use each.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. if-else:&lt;/strong&gt;&lt;br&gt;
Purpose: Evaluates a sequence of conditions and executes code based on whether a condition is true or false.&lt;br&gt;
Behavior: Each condition is checked in sequence, and the first matching condition is executed.&lt;br&gt;
Use case: Best suited for handling boolean logic, range checks, or complex conditions.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let age = 25;

if (age &amp;lt; 18) {
    console.log('Too young');
} else if (age &amp;gt;= 18 &amp;amp;&amp;amp; age &amp;lt;= 65) {
    console.log('Eligible for work');
} else {
    console.log('Retired');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;When to use:&lt;/strong&gt;&lt;br&gt;
Complex or multiple conditions: Use if-else when you need to check more complex or non-discrete conditions, such as logical combinations, ranges, or dynamic evaluations.&lt;br&gt;
Small number of conditions: Ideal for situations where there are only a few conditions to evaluate.&lt;br&gt;
Flexible condition evaluation: if-else allows you to combine logical operators (&amp;amp;&amp;amp;, ||, etc.) for more complex checks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. switch-case:&lt;/strong&gt;&lt;br&gt;
Purpose: Compares a single expression (often a variable or value) against multiple possible cases.&lt;br&gt;
Behavior: The expression is evaluated once, and the corresponding case block is executed. If no cases match, the default block runs.&lt;br&gt;
Use case: Best suited for discrete or enumerated values where multiple cases need to be evaluated.&lt;br&gt;
Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let day = 'Monday';

switch (day) {
    case 'Monday':
        console.log('Start of the week');
        break;
    case 'Wednesday':
        console.log('Midweek');
        break;
    case 'Friday':
        console.log('Almost weekend');
        break;
    default:
        console.log('Unknown day');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;When to use:&lt;/strong&gt;&lt;br&gt;
Discrete values: Use switch-case when you have a single variable that could take one of a limited number of known values (e.g., enums, constants, or states).&lt;br&gt;
Many possible values: It’s ideal when you have multiple specific cases to handle.&lt;br&gt;
Readability: switch-case makes code easier to read than using multiple if-else for discrete values.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Functions like includes() and find():&lt;/strong&gt;&lt;br&gt;
Purpose: Used to check for the existence of a value in an array (includes()) or to find an object/value within an array (find()).&lt;br&gt;
Behavior: These functions operate on arrays, returning a boolean (includes) or the found value (find).&lt;br&gt;
Use case: Best suited for array-based checks, such as finding if a value is present in a list or array of objects.&lt;/p&gt;

&lt;p&gt;Example of includes():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruits = ['apple', 'banana', 'cherry'];

if (fruits.includes('banana')) {
    console.log('We have bananas!');
} else {
    console.log('No bananas here');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example of find():&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
];

const user = users.find(user =&amp;gt; user.id === 2);
console.log(user);  // Output: { id: 2, name: 'Bob' }

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;When to use:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Array lookups: Use includes() when you want to check if a value exists in an array.&lt;br&gt;
Finding objects in arrays: Use find() when searching for an object in an array of objects based on a specific condition.&lt;br&gt;
Efficient membership tests: These methods are particularly effective when you need to check for the presence of an item in a large dataset (array).&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Running an Android App in React-Native CLI</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Thu, 20 Jun 2024 05:03:04 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/running-an-android-app-in-react-native-cli-838</link>
      <guid>https://dev.to/rajivchaulagain/running-an-android-app-in-react-native-cli-838</guid>
      <description>&lt;p&gt;This guide will walk you through the steps to run an Android app using React Native CLI. By following these steps, you can ensure your development environment is properly set up and your application runs smoothly on your connected device.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Steps&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Check Connected Devices&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Connect Your Device:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use a USB cable to connect your PC/Mac to your testing mobile 
phone.&lt;/li&gt;
&lt;li&gt;Make sure USB debugging is enabled on your mobile phone.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Check Connected Devices:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Open a terminal on your PC/Mac.&lt;/li&gt;
&lt;li&gt;Run the following command to check the list of connected devices:
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;adb devices

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;This command will show a list of devices attached. If your device appears in the list, it is correctly connected.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Clean Previous Builds&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Run the following command to clean the previous cache and builds. This helps prevent unwanted bugs:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./gradlew clean

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Run the React Native App&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Go back to the root directory of your project:&lt;/li&gt;
&lt;li&gt;Run the React Native App:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx react-native run-android

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Optional: Reset Metro Bundler Cache:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx react-native start --reset-cache

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Generate the Debug APK&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Build the Debug APK:&lt;br&gt;
 By running the previous commands, React Native will create an APK file named debug.apk for testing purposes.&lt;/p&gt;

</description>
      <category>reactnative</category>
      <category>androiddev</category>
      <category>javascript</category>
      <category>react</category>
    </item>
    <item>
      <title>Essential React Libraries for Web Development in 2024</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Fri, 07 Jun 2024 08:49:08 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/essential-react-libraries-for-web-development-in-2024-4pmn</link>
      <guid>https://dev.to/rajivchaulagain/essential-react-libraries-for-web-development-in-2024-4pmn</guid>
      <description>&lt;p&gt;In 2024, the React ecosystem is thriving with numerous libraries that significantly simplify web application development. As a React developer, I've found several libraries indispensable for creating efficient and visually appealing applications. Here's a rundown of the libraries I frequently use and recommend:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;UI Library:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Mantine UI: In 2024, Mantine UI has become my go-to choice for a comprehensive UI library. It stands out due to its unique and highly practical components that are ready to use out of the box. This library eliminates the need to design components from scratch, allowing developers to focus more on functionality. Mantine also offers its own hooks for form state management, which is incredibly convenient. For handling complex tables, I rely on mantine-react-table. I highly recommend trying Mantine UI in your projects and sharing your experience.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;State Management (Global and Server-Side):&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For global state management, I use a combination of react-hooks with react-context and react-reducer hooks. For smaller state management tasks, I sometimes incorporate react-stateful hooks.&lt;br&gt;
For server-side data fetching, react-query is my preferred choice. It efficiently handles data fetching and mutations, making server-side state management straightforward. I also use axios for making HTTP requests, which pairs well with react-query.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Charts:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While Mantine provides some minimal charting capabilities, for more complex charting needs, I turn to nivo charts. Nivo offers a rich set of features for creating beautiful and interactive charts.&lt;br&gt;
PDF Generation:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;For generating PDFs&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;react-to-pdf is my tool of choice. It simplifies the process of converting React components into PDF documents, making it a valuable addition to my development toolkit.&lt;/p&gt;

&lt;p&gt;These libraries have proven to be incredibly valuable in my development workflow, enhancing productivity and the overall quality of the applications I build. I encourage you to explore these tools and see how they can benefit your projects.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Let's print fibonacci series with js with all explanation and problem solving.</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Thu, 20 Oct 2022 07:44:39 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/lets-print-fibonacci-series-with-js-with-all-explanation-and-problem-solving-c2n</link>
      <guid>https://dev.to/rajivchaulagain/lets-print-fibonacci-series-with-js-with-all-explanation-and-problem-solving-c2n</guid>
      <description>&lt;p&gt;Here, Problem solving is the only skill a programmer needs so I would like to show some case for it.&lt;br&gt;
In above question we can find that we have to print fibonacci series,&lt;/p&gt;

&lt;p&gt;Now fibonacci series looks like this :&lt;br&gt;
&lt;code&gt;1 , 1, 2 , 3 , 5 , 8 ......&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
Now, we have to print this fibonacci series so first thing we need is the pattern here , we find that the first number and second number while adding gives the third number. &lt;br&gt;
For eg : 1 + 1 -&amp;gt; 2 , 1 + 2 -&amp;gt; 3 , 2 + 3 -&amp;gt; 5 .&lt;/p&gt;

&lt;p&gt;woo we found the pattern half of the solution is done. Try solving this problem into some paper before writing on code.&lt;br&gt;
Then start coding immediately&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let a = 0;
let b = 1;
let c;
for (let index = 0; index &amp;lt; 10; index++) {
    console.log(b);
    c = a + b
    a = b 
    b = c
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now what we have done .&lt;br&gt;
1 -&amp;gt; Declaring variable a , b ,c &lt;br&gt;
2 -&amp;gt; looping so that we can get how much interval or value we want&lt;br&gt;
3 -&amp;gt; logging the first value as b that gives 1.&lt;br&gt;
4 -&amp;gt; Now variable c adds two variable 1 and 0 in initial&lt;br&gt;
5 -&amp;gt; a takes value of b and b takes value of c &lt;/p&gt;

&lt;p&gt;Conclusion,&lt;br&gt;
Hence this is about the problem solving not about coding&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>How to Get Started With React – A Beginner's Guide Part -2</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Mon, 17 Oct 2022 10:20:46 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/how-to-get-started-with-react-a-beginners-guidepart-2-269m</link>
      <guid>https://dev.to/rajivchaulagain/how-to-get-started-with-react-a-beginners-guidepart-2-269m</guid>
      <description>&lt;p&gt;If you have read my first blog then you have got some tips about starting with react js. Today let's learn more about react js and start creating your web apps.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why react js ?
&lt;/h2&gt;

&lt;p&gt;-&amp;gt; React js is very popular library and it is popular because you can create your app with minimal code meaning you can write code once and reuse it again and  again so the development would be faster and also react uses some extensions like jsx which lets you use html tags with javascript so that you have no need to append or manipulate dom , in simple  terms React js is declarative.&lt;/p&gt;

&lt;h2&gt;
  
  
  Virtual vs Real Dom.
&lt;/h2&gt;

&lt;p&gt;-&amp;gt; If you are familiar with Js then you might know about DOM. Dom is basically a Document model in browser that contains the html elements or tags. Basically with help of js we manipulate those DOM elements to create an awesome user experience. So in react ,the concept of virtual dom is quite interesting.React js creates a virtual dom that takes all our work rather than in real dom and when we work during development our components are rendered as tree structure in virtual dom.React then compares out virtual dom with real-dom and only changes those components that's need to be changed meaning it doesn't change all the code overtime so , our app would render much faster than the ordinary , typical websites. for eg , if you create a component and render the date in the component then you can find the component only is ticking rather than the whole page.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsgeaa4mn019et3flgsig.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsgeaa4mn019et3flgsig.png" alt="Virtual dom vs real dom" width="610" height="444"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To get start with react there is a package so simply create &lt;br&gt;
your development server with below code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app my-app

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

&lt;/div&gt;



&lt;p&gt;Now , you have created a react app named as my-app&lt;br&gt;
now if you go to the package.json -&amp;gt; scripts you can find something like this,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Start -&amp;gt; It starts your react app eg, npm start&lt;/li&gt;
&lt;li&gt;Build -&amp;gt; It build your app for production and genrates a static file. eg, npm run build,&lt;/li&gt;
&lt;li&gt;Test -&amp;gt; It is used to test you app or any components.&lt;/li&gt;
&lt;li&gt;Eject -&amp;gt; If you want to revert the app then eject.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;so, when we do npm start , the development start's in port 3000;&lt;/p&gt;

&lt;p&gt;Now you can find the main file index.js that renders our whole app using react-dom. The code looks like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom/client';

import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
          &amp;lt;React.StrictMode&amp;gt;
            &amp;lt;App /&amp;gt;
          &amp;lt;/React.StrictMode&amp;gt;
);

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

&lt;/div&gt;



&lt;p&gt;Here, basically we have appended our app component to the div tag.There is only one html tag with &lt;/p&gt;.&lt;br&gt;
We take this root and append our js inside this div tag.&lt;br&gt;
Now , our App.js we will be rendered and it is termed as a component in react js.
&lt;h2&gt;
  
  
  1. Component in react js.
&lt;/h2&gt;

&lt;p&gt;-&amp;gt; In react js ,component is termed as the building block. We create small components and later enscapulate them to create a complex UI.Component basically takes props as input and returns jsx.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqjwh6cdp2ok1491znw7t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqjwh6cdp2ok1491znw7t.png" alt="Component render method" width="800" height="695"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In App.js,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const App = (some props) =&amp;gt; {

   return (
    // it returns jsx 
   // &amp;lt;&amp;gt; &amp;lt;/&amp;gt; this is and react fragment.
      &amp;lt;&amp;gt;This an simple app&amp;lt;/&amp;gt;
 )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here , we created an simple App component and hence some rules of component are :&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Use first letter of component as capital eg : App , Navbar etc. else it will be treated as regular functions.&lt;/li&gt;
&lt;li&gt;Call the component by  close the tag else JSX treat it as error.&lt;/li&gt;
&lt;li&gt;You can nest as much as components as you want.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;for eg :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const Navbar = () =&amp;gt; {
return (
&amp;lt;div&amp;gt;This is a navbar&amp;lt;/div&amp;gt;
)
};

export const App = () =&amp;gt; {
return (
&amp;lt;App /&amp;gt;
)}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. JSX
&lt;/h2&gt;

&lt;p&gt;-&amp;gt; JSX is simply an javascript xml that helps to use html and javascript in single place&lt;br&gt;
for eg :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const App = () =&amp;gt; {
   const name = "rajiv";
    return (
     &amp;lt;h1&amp;gt;My name is {name}&amp;lt;/h1&amp;gt;
)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Some rules while using JSX are :&lt;br&gt;
a. Component should have only one div tag.&lt;br&gt;
eg:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const App = () =&amp;gt; {
return (
   &amp;lt;&amp;gt;Hello&amp;lt;/&amp;gt;
   &amp;lt;&amp;gt;Wow&amp;lt;/&amp;gt;
)};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It throws error so , it would be wrap on single tag.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn9oqh0e6hy2cwv7neecc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn9oqh0e6hy2cwv7neecc.png" alt="Javascript xml" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;b. Jsx is compiled to normal html by babel.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion,
&lt;/h2&gt;

&lt;p&gt;I guess now you can get started and I will bring part-3. Till then if any problem consult me ,&lt;br&gt;
&lt;a href="https://www.facebook.com/Rajiv.chaulgain/" rel="noopener noreferrer"&gt;https://www.facebook.com/Rajiv.chaulgain/&lt;/a&gt;,&lt;br&gt;
&lt;a href="https://github.com/rajivchaulagain" rel="noopener noreferrer"&gt;https://github.com/rajivchaulagain&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How to Get Started With React – A Beginner's Guide</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Sat, 15 Oct 2022 06:14:05 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/get-started-with-react-js-1nkb</link>
      <guid>https://dev.to/rajivchaulagain/get-started-with-react-js-1nkb</guid>
      <description>&lt;p&gt;React js is a javascript library and it is also termed as a framework because it can be directly be compared with javascript frameworks like angular , view.&lt;/p&gt;

&lt;p&gt;Most people including me used react because of it’s huge community support and you can find many article and solutions like this about react js everywhere on goggle.&lt;/p&gt;

&lt;p&gt;I used react js because it was so popular and in demand , but after using it I felt that this is the fastest way to design web apps and It was amazing experience while coding because now frontend is not only about designing but it is also about implementing business logics and techniques.&lt;/p&gt;

&lt;p&gt;Many developers want to learn react but learning react can be difficult if you directly jump into in without learning basics of Javascript.&lt;/p&gt;

&lt;p&gt;Some of the terms to be learned before diving into react js are :&lt;/p&gt;

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

&lt;p&gt;— Learn basics of HTML 5 like div tags , classes and id’s of HTML and stuffs like semantic tags as (section , aside , header , footer);&lt;/p&gt;

&lt;h2&gt;
  
  
  CSS
&lt;/h2&gt;

&lt;p&gt;— Learning CSS helps to learn react js faster cause styling is necessity for front-end developers.&lt;/p&gt;

&lt;h2&gt;
  
  
  JAVASCRIPT
&lt;/h2&gt;

&lt;p&gt;— Learning basics of Js is important as what we use is only ES6 stand for EcmaScript 2015. Learn following things in ES6 like : map method , filter method , template strings , var , let , const , hoisting , arrow functions , this keyword , class in js , OOP in js , destructuring etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  REACT DOCS
&lt;/h2&gt;

&lt;p&gt;— Learn react docs more than anything in world then you feel react js is so easy that a common man learn do it within months.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Now, create more projects like todolist, ecommerce website, api covid tracker and many crud projects to be used in react.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to upload image with base64 and validate it with formik</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Sat, 15 Oct 2022 06:08:07 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/uploading-image-with-formik-and-base64-2loa</link>
      <guid>https://dev.to/rajivchaulagain/uploading-image-with-formik-and-base64-2loa</guid>
      <description>&lt;p&gt;Lets upload image with formik and react js.&lt;/p&gt;

&lt;p&gt;Now,Base64 is a group of binary-to-text encoding schemes that represent binary data (more specifically, a sequence of 8-bit bytes) in sequences of 24 bits that can be represented by four 6-bit Base64 digits.&lt;/p&gt;

&lt;p&gt;Now we will create a single image .&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const singleImage = () =&amp;gt; {

 const convertToBase64 = (file) =&amp;gt; {
    return new Promise((resolve, reject) =&amp;gt; {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () =&amp;gt; {
        resolve(fileReader.result);
      };
      fileReader.onerror = (error) =&amp;gt; {
        reject(error);
      };
    });
  };

  const handleIcon = async (e, setFieldValue) =&amp;gt; {
    const file = e.target.files[0];
       //check the size of image 
    if (file?.size/1024/1024 &amp;lt; 2) {
      const base64 = await convertToBase64(file);
      setFieldValue('profile_image', base64);
    }
    else {
      toast.error('Image size must be of 2MB or less');
    };
  };

  return (
       &amp;lt;div className="mb-3 form-group"&amp;gt;
          &amp;lt;label className="required"&amp;gt;Upload Photo&amp;lt;/label&amp;gt;
               &amp;lt;Field name='profile_image'&amp;gt;
                   {({ form, field }) =&amp;gt; {
                     const { setFieldValue } = form
                        return (
                          &amp;lt;input
                            type="file"
                             className='form-control'
                              required
                          onChange={(e) =&amp;gt; handleIcon(e, setFieldValue)}
                             /&amp;gt;
                            )
                          }}
                     &amp;lt;/Field&amp;gt;
                   &amp;lt;div className="text-danger"&amp;gt;
               &amp;lt;ErrorMessage name="profile_image" /&amp;gt;
         &amp;lt;/div&amp;gt;
     &amp;lt;/div&amp;gt;
 )
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, here formik handles the image and then we take the image from onchange function and check the size and if the size is less than the condition then , convertToBase64 function converts the image into base64 as string and hence the image is converted to base64.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multipleImage = () =&amp;gt; {

export const convertToBase64 = (file) =&amp;gt; {
    return new Promise((resolve, reject) =&amp;gt; {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = () =&amp;gt; {
        resolve(fileReader.result);
      };
      fileReader.onerror = (error) =&amp;gt; {
        reject(error);
      };
    });
  };

const handleProfile = async (e, setFieldValue) =&amp;gt; {
    const file = e.target.files[0];
    if (file?.size / 1024 / 1024 &amp;lt; 2) {
        const base64 = await convertToBase64(file);
        setFieldValue('image', base64);
    }
    else {
        toast.error('Image size must be of 2MB or less');
    };

return (
          &amp;lt;div className="mb-3 form-group"&amp;gt;
            &amp;lt;label&amp;gt;Upload Cover Photo&amp;lt;/label&amp;gt;
            &amp;lt;Field name={name}&amp;gt;
                {({ form, field }) =&amp;gt; {
                    const { setFieldValue } = form
                    return (
                        &amp;lt;input
                            type="file"
                            className='form-control'
                            onChange={(e) =&amp;gt; handleProfile(e, setFieldValue)}
                        /&amp;gt;
                    )
                }}
            &amp;lt;/Field&amp;gt;
        &amp;lt;/div&amp;gt;
)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Hence in the formik data we can find our image as converted to base64.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>React Query Custom Hooks Example in react js</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Sat, 15 Oct 2022 04:39:53 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/adding-custom-hook-with-react-query-in-react-js-41ef</link>
      <guid>https://dev.to/rajivchaulagain/adding-custom-hook-with-react-query-in-react-js-41ef</guid>
      <description>&lt;p&gt;Let's create a custom hook with react query.&lt;br&gt;
Now we will create a component that fetches list of products with react query.&lt;/p&gt;

&lt;p&gt;Now in Product.js component ,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Product = () =&amp;gt; {
  const products = useProducts()
   if(products.isLoading) return "Loading ....."
   if(products.isError) return "Error ...." 
  return(
   &amp;lt;&amp;gt;
      products.map((product) =&amp;gt; (
     &amp;lt;h4 key={product.id}&amp;gt;{product.title}&amp;lt;/h4&amp;gt;
  ))
   &amp;lt;/&amp;gt;
)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lets create a hook as useProducts.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const useProducts = () =&amp;gt; {
  return useQuery(['products'] , getProducts)
};

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

&lt;/div&gt;



&lt;p&gt;Now if we want to fetch single data then we can pass id&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Product = () =&amp;gt; {
const params = useParams();
const id = Number(params?.id)
  const product = useProduct(id)
   if(product.isLoading) return "Loading ....."
   if(product.isError) return "Error ...." 
  return(
   &amp;lt;&amp;gt;
     &amp;lt;h4&amp;gt;{product.title}&amp;lt;/h4&amp;gt;
  ))
   &amp;lt;/&amp;gt;
)
}

const useProduct = (id) =&amp;gt; {
  return useQuery(['product' , id] , () =&amp;gt; getProduct(id))
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now for post and edit,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const AddProduct = () =&amp;gt; {
  const mutation = useAddProduct()
  const [data , setData] = useState('');
  return(
   &amp;lt;&amp;gt;
    &amp;lt;input value={data} onChange={(e) =&amp;gt; 
        setData(e.target.value) } /&amp;gt; 
    &amp;lt;button onClick={mutation.mutate(data)}&amp;gt;&amp;lt;/button&amp;gt;
   &amp;lt;/&amp;gt;
  )
)
};

const useAddProduct = () =&amp;gt; {
  return useMutation(postProduct , {
  onSuccess : () =&amp;gt; {
    toast.success(`Added successfully`)
  }
})
};

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

&lt;/div&gt;



&lt;p&gt;for edit ,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const EditProduct = () =&amp;gt; {
  const params = useParams();
  const id = Number(params.id);
  const mutation = useEditProduct()
  const [data , setData] = useState('');
  return(
   &amp;lt;&amp;gt;
    &amp;lt;input value={data} onChange={(e) =&amp;gt; 
        setData(e.target.value) } /&amp;gt; 
    &amp;lt;button onClick={mutation.mutate(data , id)}&amp;gt;&amp;lt;/button&amp;gt;
   &amp;lt;/&amp;gt;
  )
)
};

const useEditProduct = () =&amp;gt; {
  return useMutation(editProduct , {
  onSuccess : () =&amp;gt; {
    toast.success(`edited successfully`)
  }
})
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion,
&lt;/h2&gt;

&lt;p&gt;This is the best way to manage the server side data and separate the business logics with the UI components and hence anyone from outer world can check , edit and understand the code. This is the best way to work with react and only the needed component will use the data from the custom hook.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>React Hook Form - Combined Add/Edit (Create/Update) Form Example</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Fri, 14 Oct 2022 15:59:45 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/lets-create-an-addedit-with-same-component-3b2j</link>
      <guid>https://dev.to/rajivchaulagain/lets-create-an-addedit-with-same-component-3b2j</guid>
      <description>&lt;p&gt;Today we are going to perform a crud app where we will add and edit the form with same component .&lt;br&gt;
We will use react-router-dom , formik and yup. so let's dive to the code.&lt;/p&gt;

&lt;p&gt;Create a component as AddEdit.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useEffect, useState } from 'react'
import { Formik, Form } from 'formik'
import { useMutation, useQuery, useQueryClient } from 'react-query'


const AddEdit = () =&amp;gt; {

  const history = useHistory()

  const user = useUser()

  const params: any = useParams()

  const queryClient = useQueryClient()

  const id: number = Number(params?.id)

  const isAddMode = !id

  const { data, isLoading, isError } = useQuery(['data', id], () =&amp;gt; getData(id), {
    enabled: !!id,
  })

  const onFormSubmit = (values: any) =&amp;gt; {
    isAddMode ? addFnc : editFnc
  }

  const initValues = {
    name: isAddMode ? '' : data?.name
  }

  return (
    &amp;lt;&amp;gt;
      &amp;lt;div className=''&amp;gt;
        &amp;lt;Formik validationSchema={Schema} initialValues= {initValues} onSubmit={onFormSubmit}&amp;gt;
          {(props) =&amp;gt; (
            &amp;lt;Form className='w-100 pb-10'&amp;gt;
              &amp;lt;Field name="name" /&amp;gt;
              &amp;lt;button
                type='submit'&amp;gt;
                  'Submit'
              &amp;lt;/button&amp;gt;
            &amp;lt;/Form&amp;gt;
          )}
        &amp;lt;/Formik&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  )
}

export default AddEdit
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So here , we created a function and hence we added the code.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>typescript</category>
    </item>
    <item>
      <title>React Hooks : How to use Authorization in react js with custom hook.</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Fri, 14 Oct 2022 15:31:35 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/authorization-in-react-js-with-custom-hook-23dp</link>
      <guid>https://dev.to/rajivchaulagain/authorization-in-react-js-with-custom-hook-23dp</guid>
      <description>&lt;h2&gt;
  
  
  Here today I am gonna use custom hook and create a authorization for admin and other manager roles.
&lt;/h2&gt;

&lt;p&gt;Lets start by creating a custom hook as useUserRole.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {useEffect} from 'react'
import { toast } from 'react-toastify'

import {useAuth} from './useAuth'

export const useUserRole = (allowedRoles) =&amp;gt; {
  const {session} = useAuth()
  useEffect(() =&amp;gt; {
    if (!allowedRoles.includes(session?.user?.role)) {
      localStorage.removeItem('session')
      window.location.reload()
      toast.error(`Unauthorized`)
    }
  }, [allowedRoles , session])
  return true
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;here , we created an custom hook that takes allowedRoles and we are checking the allowedRoles with the role on our session during the login&lt;/p&gt;

&lt;p&gt;here the condition is , if the allowedRoles is equal to the role in session then they are allowed to view the provided route else they will be redirect to login page.&lt;/p&gt;

&lt;p&gt;Now we can specify the roles.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const ROLE = {
  Admin: 'Admin',
  Manager: 'Manager',
  User: 'User'
}

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

&lt;/div&gt;



&lt;p&gt;Now in any component like Blog.js&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
import React, { useState } from 'react'

import { useUserRole } from '../../../hooks/useUserRole'
import { ROLE } from '../../../_helpers/Role'

const Blog = () =&amp;gt; {

//checking the role
  useUserRole([ROLE.Admin]);

  return ( 
        &amp;lt;&amp;gt;Blog page&amp;lt;/&amp;gt;
  )
}

export default Blog
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Hence , the authorization is success and hence we can reuse the hook for the protected routes.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
      <category>auth</category>
    </item>
    <item>
      <title>TanStack Query v4 Powerful asynchronous state management for TS/JS, React, Solid, Vue and Svelte</title>
      <dc:creator>Rajiv Chaulagain</dc:creator>
      <pubDate>Fri, 14 Oct 2022 15:22:39 +0000</pubDate>
      <link>https://dev.to/rajivchaulagain/tanstack-query-v4powerful-asynchronous-state-management-for-tsjs-react-solid-vue-and-svelte-2gdl</link>
      <guid>https://dev.to/rajivchaulagain/tanstack-query-v4powerful-asynchronous-state-management-for-tsjs-react-solid-vue-and-svelte-2gdl</guid>
      <description>&lt;h2&gt;
  
  
  Let's learn react query V4.
&lt;/h2&gt;

&lt;p&gt;React Query is often described as the missing data-fetching library for React. Still, in more technical terms, it makes fetching, caching, synchronizing, and updating server state in your React applications a breeze.&lt;/p&gt;

&lt;p&gt;Why react query ?&lt;br&gt;
 -&amp;gt; React query as often said is used for state management of server data and using react query the we should write less code so it is also an alternate of redux toolkit.&lt;/p&gt;

&lt;p&gt;Starting with react-query we need to provide a context provider given by react-query and then we can use the hook provided by react-query , Let's look onto and example.&lt;/p&gt;

&lt;p&gt;In app.js file configure by following ways,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
  useQueryClient,
  QueryClient,
  QueryClientProvider,
} from '@tanstack/react-query'

// Create a client
const queryClient = new QueryClient()

export function App() {
  return (
    // Provide the client to your App
    &amp;lt;QueryClientProvider client={queryClient}&amp;gt;
    //out app goes here......
    &amp;lt;/QueryClientProvider&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now inside our component we can access the data.&lt;/p&gt;

&lt;p&gt;So for fetching data in component Products.js ,&lt;/p&gt;

&lt;p&gt;`import {&lt;br&gt;
  useQuery,&lt;br&gt;
} from '@tanstack/react-query'&lt;br&gt;
import { getProducts } from '../my-api'&lt;/p&gt;

&lt;p&gt;function Products() {&lt;/p&gt;

&lt;p&gt;// Queries&lt;br&gt;
  const {data , isLoading , isError} = useQuery(['products'], getProducts)&lt;br&gt;
if(isLoading) return "Loading ..."&lt;br&gt;
if(isError) return "Error ..."&lt;/p&gt;

&lt;p&gt;//then we can assume the data is success&lt;/p&gt;

&lt;p&gt;return (&lt;br&gt;
    &lt;/p&gt;
&lt;br&gt;
      &lt;ul&gt;

        {data?.map(product =&amp;gt; (
          &lt;li&gt;{product.title}&lt;/li&gt;

        ))}
      &lt;/ul&gt;
&lt;br&gt;
    &lt;br&gt;
  )&lt;br&gt;
}`

&lt;p&gt;Here , we provided and unique key as "products" inside useQuery hook that provides the caching and it should be unique.&lt;br&gt;
The getProducts function is a promise based function that returns data if success and throws error if any error&lt;/p&gt;

&lt;p&gt;Here we used the hook called useQuery from react-query that provides following things.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;data -&amp;gt; It gives the data from server eg : data : [{title : 'title'}]&lt;/li&gt;
&lt;li&gt;isLoading -&amp;gt; It provides the loading state as boolean and till our data is being fetched and currently in loading state.&lt;/li&gt;
&lt;li&gt;isError -&amp;gt; if there is any problem while fetching data the error will be provided on error state.
some more ways are :-&lt;/li&gt;
&lt;li&gt;error -&amp;gt; It provides the error message .&lt;/li&gt;
&lt;li&gt;isFetching -&amp;gt; after every render react-query fetches and isFetching will be true while isLoading is only true during initial render.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now for posting data we use Next hook as useMutation .&lt;/p&gt;

&lt;p&gt;so In AddProduct Component ,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
mport {
  useMutation,
  useQueryClient,
} from '@tanstack/react-query';

const AddProducts = () =&amp;gt; {
const [data , setData] = useState('');
 // Access the client
  const queryClient = useQueryClient();

const mutation = useMutation(mutationFn , {
onSuccess : () =&amp;gt; {
   // Invalidate and refetch
      queryClient.invalidateQueries(['products'])}
}
)

return (
&amp;lt;&amp;gt;
  &amp;lt;input value={data} setData={(e) =&amp;gt; setData(e.target.value)} /&amp;gt;
&amp;lt;button onClick={mutation.mutate(data)}&amp;gt;Submit&amp;lt;/button&amp;gt; 
&amp;lt;/&amp;gt;
)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, useMutation hooks take mutation function.&lt;br&gt;
here mutate is the callback function that takes the data and provides in useMutation hook.&lt;/p&gt;

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