<?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 Sabhya Saini on Medium]]></title>
        <description><![CDATA[Stories by Sabhya Saini on Medium]]></description>
        <link>https://medium.com/@sabhya12.saini?source=rss-d94d5b1350b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nZXggeTgVb7dtuJuIa37Lw.jpeg</url>
            <title>Stories by Sabhya Saini on Medium</title>
            <link>https://medium.com/@sabhya12.saini?source=rss-d94d5b1350b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:19:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sabhya12.saini/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[How to send form data from React JS directly to the email address using Formspree]]></title>
            <link>https://medium.com/@sabhya12.saini/how-to-send-form-data-from-react-js-directly-to-the-email-address-using-formspree-69807d4a78ac?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/69807d4a78ac</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[form-to-email]]></category>
            <category><![CDATA[formspree]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 14:55:46 GMT</pubDate>
            <atom:updated>2023-10-13T14:55:46.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*_1cX_cRB4R4ZJxHSdkDXCA.png" /><figcaption>React JS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E2TD94XPwCspws3BzuCJqQ.png" /></figure><p>Steps to configure Formspree<br>1. Register to Formspree : <a href="https://formspree.io/">https://formspree.io/</a></p><p>2. Click to create a form. <br>Make sure you have verified your email where you wish to receive the form data. One account can have maximum two emails in the free tier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69ECLEYvP0mDfo5_-XOHmA.png" /></figure><p>3. Click on “Create Form”</p><p>4. Once the form is created, you can see the various code snippets provided to you from Formspree. As we are using React, here is how the code looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NK7jvDxilEZYX9t2ASPBQ.png" /></figure><p>To enhance the experience of the form submission, here is how I have used UseEffect hook to control the state of form submission if the form validation isn’t successful :</p><pre>//Packages<br>import React, { useState, useEffect } from &quot;react&quot;;<br>import { Grid } from &quot;@mui/material&quot;;<br>import { useForm, ValidationError } from &quot;@formspree/react&quot;;<br>//Assets<br>import SubmitButton from &quot;../components/button/SubmitButton&quot;;<br><br>function ContactUs() {<br>  const [formData, setFormData] = useState({<br>    name: &quot;&quot;,<br>    email: &quot;&quot;,<br>    phoneNumber: &quot;&quot;,<br>  });<br>  const [state, handleSubmit] = useForm(&quot;xoqoywry&quot;);<br>  useEffect(() =&gt; {<br>    if (state.succeeded) {<br>      alert(&quot;Subscribed to our newsletter successfully&quot;);<br>      setFormData({<br>        name: &quot;&quot;,<br>        email: &quot;&quot;,<br>        phoneNumber: &quot;&quot;,<br>      });<br>    }<br>  }, [state.succeeded]);<br><br>  const handleChange = (e) =&gt; {<br>    const { name, value } = e.target;<br>    setFormData({<br>      ...formData,<br>      [name]: value,<br>    });<br>  };<br><br>  return (<br>    &lt;Grid container columns={12} mt={30}&gt;<br>      &lt;form onSubmit={handleSubmit} style={{ width: &quot;100%&quot; ,height:&#39;150vh&#39;}}&gt;<br>        &lt;Grid<br>          container<br>          columns={6}<br>          display=&quot;flex&quot;<br>          flexDirection=&quot;column&quot;<br>          className=&quot;glassmorphism-card&quot;<br>          marginInline=&quot;auto&quot;<br>          width=&quot;65%&quot;<br>          height=&#39;120%&#39;<br>          borderRadius=&quot;5px&quot;<br>          textAlign=&quot;left&quot;<br>          padding=&quot;3rem&quot;<br>        &gt;<br>          &lt;div className=&quot;glassmorphism-card-content&quot;&gt;<br>            &lt;div className=&quot;inputdiv&quot;&gt;<br>              &lt;label&gt;Name *&lt;/label&gt;<br>              &lt;input<br>                type=&quot;text&quot;<br>                name=&quot;name&quot;<br>                value={formData.name}<br>                onChange={handleChange}<br>                required<br>              /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;inputdiv&quot;&gt;<br>              &lt;label&gt;Email *&lt;/label&gt;<br>              &lt;input<br>                type=&quot;email&quot;<br>                name=&quot;email&quot;<br>                value={formData.email}<br>                onChange={handleChange}<br>                required<br>              /&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;inputdiv&quot;&gt;<br>              &lt;label&gt;Phone Number *&lt;/label&gt;<br>              &lt;input<br>                type=&quot;tel&quot;<br>                name=&quot;phoneNumber&quot;<br>                value={formData.phoneNumber}<br>                onChange={handleChange}<br>                required<br>                pattern=&quot;[0-9]{10}&quot;<br>              /&gt;<br>            &lt;/div&gt;<br><br>            &lt;SubmitButton<br>              type=&quot;submit&quot;<br>              variant=&quot;outlined&quot;<br>              style={{<br>                marginBlock: &quot;10%&quot;,<br>              }}<br>            &gt;<br>              &lt;b style={{ color: &quot;#ffc333&quot; }} className=&quot;mont&quot;&gt;<br>                Submit<br>              &lt;/b&gt;<br>            &lt;/SubmitButton&gt;<br>            &lt;ValidationError<br>              prefix=&quot;Message&quot;<br>              field=&quot;message&quot;<br>              errors={state.errors}<br>            /&gt;<br>          &lt;/div&gt;<br>        &lt;/Grid&gt;<br>      &lt;/form&gt;<br>    &lt;/Grid&gt;<br>  );<br>}<br><br>export default ContactUs;</pre><p>5. Run the code using <strong>npm start. <br> </strong>Following is the output of the same :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBBxIWaiFOTKrt_Pn9NO0Q.png" /></figure><p>6. Test the email received. <br>You must have received an email in your inbox. You can directly reply to the email sent in the form data by clicking on the reply button.</p><p>7. Monthly 50 emails are available in the free tier. You can also check the Formspree dashboard for the emails received and their status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ex4Chefv0NbapOP5nDExmQ.png" /></figure><p>Hope it helped you expedite your process of development, if you have been searching for this solution.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69807d4a78ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating PayU payment gateway in React Native]]></title>
            <link>https://medium.com/@sabhya12.saini/integrating-payu-payment-gateway-in-react-native-1c891293a3b?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c891293a3b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[payu]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[checkout]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 12:57:45 GMT</pubDate>
            <atom:updated>2024-01-23T09:22:22.332Z</atom:updated>
            <content:encoded><![CDATA[<p>I have found integrating payment gateways in my apps difficult from the documentation provided by the service providers. As soon as I am able to find the solution, I write an article about the same here at medium, so that the next human doesn’t have to go through much hassle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47m8C2JzYdCc0bSSz-44Mg.png" /><figcaption><a href="https://payu.in/developer-guide">https://payu.in/developer-guide</a></figcaption></figure><ol><li>Create React Native App<br><a href="https://reactnative.dev/docs/environment-setup"><em>https://reactnative.dev/docs/environment-setup</em></a></li></ol><pre>npx react-native@latest init PayuGateway</pre><p>2. Add package</p><pre>yarn add payu-non-seam-less-react</pre><p><em>Note : You may get an error for ‘classifier’ inside node_modules&gt;payu-non-seam-less-react&gt;android&gt;build.gradle. Update the classifier to ‘archiveClassifier’ and it will remove the error.</em></p><p>Also make sure that at in your <em>android&gt;app&gt;build.gradle</em> these two lines are present inside your dependencies section : <br><em>implementation(‘in.payu:payu-checkout-pro:2.0.19’)<br>implementation project(‘:payu-non-seam-less-react’)</em></p><p>and inside android section : <br>compileOptions {<br>sourceCompatibility JavaVersion.VERSION_1_8<br>targetCompatibility JavaVersion.VERSION_1_8<br>}</p><p>these lines are present, if not add these.</p><p>3. Create frontend -React Native file named Checkout.js</p><pre>// Packages<br>import {<br>  TouchableOpacity,<br>  NativeEventEmitter,<br>  NativeModules,<br>  Alert,<br>} from &#39;react-native&#39;;<br>import React, {<br>  useState,<br>  useContext,<br>  useEffect,<br>} from &#39;react&#39;;<br>import auth from &#39;@react-native-firebase/auth&#39;;<br>import {PAYU_KEY} from &#39;@env&#39;;<br>//Components<br>import {Text} from &#39;../components/Themed&#39;;<br>import {RootTabScreenProps} from &#39;../../types&#39;;<br>// Styles<br>import shipstyle from &#39;../styles/Ship.styles&#39;;<br><br><br>const {PayUBizSdk} = NativeModules;<br><br><br>const Checkout = ({navigation, route}: RootTabScreenProps&lt;&#39;Cart&#39;&gt;) =&gt; {<br><br>  const {generateResponseHash, addOrder, addMyOrder} = orderContext;<br><br>  let totalprice = route?.params;<br><br><br><br>  const [android_surl, setAndroidSurl] = useState(<br>    &#39;https://payu.herokuapp.com/success&#39;,<br>  );<br>  const [android_furl, setAndroidFurl] = useState(<br>    &#39;https://payu.herokuapp.com/failure&#39;,<br>  );<br><br>  const [<br>    showExitConfirmationOnCheckoutScreen,<br>    setShowExitConfirmationOnCheckoutScreen,<br>  ] = useState(true);<br>  const [<br>    showExitConfirmationOnPaymentScreen,<br>    setShowExitConfirmationOnPaymentScreen,<br>  ] = useState(true);<br><br>  const [cartDetails, setCartDetails] = useState(carts);<br>  const [paymentModesOrder, setPaymentModesOrder] = useState([<br>    {UPI: &#39;TEZ&#39;},<br>    {Wallets: &#39;PAYTM&#39;},<br>    {EMI: &#39;&#39;},<br>    {Wallets: &#39;PHONEPE&#39;},<br>  ]);<br>  const [surePayCount, setSurePayCount] = useState(1);<br>  const [merchantResponseTimeout, setMerchantResponseTimeout] = useState(10000);<br>  //const [showExitConfirmationOnPaymentScreen, setShowExitConfirmationOnPaymentScreen] = useState(true);<br>  const [autoSelectOtp, setAutoSelectOtp] = useState(true);<br>  const [enforcePaymentEnable, setEnforcePaymentEnable] = useState(false);<br>  const [showCbToolbar, setShowCbToolbar] = useState(true);<br>  const [autoApprove, setAutoApprove] = useState(false);<br>  const [merchantSMSPermission, setMerchantSMSPermission] = useState(false);<br>  const [showAlert, setShowAlert] = useState(false);<br><br>  const displayAlert = (title, value) =&gt; {<br>    if (showAlert == false) {<br>      console.log(&#39;displayAlert &#39; + title + &#39; &#39; + value);<br>      setShowAlert(true);<br>      Alert.alert(title, value);<br>    }<br>    setShowAlert(false);<br>  };<br><br>  useEffect(() =&gt; {<br>    const eventEmitter = new NativeEventEmitter(PayUBizSdk);<br><br>    payUOnPaymentSuccess = eventEmitter.addListener(<br>      &#39;onPaymentSuccess&#39;,<br>      onPaymentSuccess,<br>    );<br>    payUOnPaymentFailure = eventEmitter.addListener(<br>      &#39;onPaymentFailure&#39;,<br>      onPaymentFailure,<br>    );<br>    payUOnPaymentCancel = eventEmitter.addListener(<br>      &#39;onPaymentCancel&#39;,<br>      onPaymentCancel,<br>    );<br>    payUOnError = eventEmitter.addListener(&#39;onError&#39;, onError);<br>    payUGenerateHash = eventEmitter.addListener(&#39;generateHash&#39;, generateHash);<br>    //Unregister eventEmitters here<br>    return () =&gt; {<br>      console.log(&#39;Unsubscribed!!!!&#39;);<br>      payUOnPaymentSuccess.remove();<br>      payUOnPaymentFailure.remove();<br>      payUOnPaymentCancel.remove();<br>      payUOnError.remove();<br>      payUGenerateHash.remove();<br>    };<br>  }, [result]);<br>  // Define event handlers for different payment events<br>  // Define event handlers for different payment events<br>  const onPaymentSuccess = e =&gt; {<br>    console.log(e.merchantResponse);<br>    console.log(e.payuResponse);<br>    displayAlert(&#39;onPaymentSuccess&#39;, JSON.stringify(e));<br>  };<br>  const onPaymentFailure = e =&gt; {<br>    console.log(e);<br>    console.log(e.merchantResponse);<br>    console.log(e.payuResponse);<br>    displayAlert(&#39;onPaymentFailure&#39;, JSON.stringify(e));<br>  };<br>  const onPaymentCancel = e =&gt; {<br>    console.log(&#39;onPaymentCancel isTxnInitiated -&#39; + e);<br>    displayAlert(&#39;onPaymentCancel&#39;, JSON.stringify(e));<br>  };<br>  const onError = e =&gt; {<br>    console.log(e);<br>    displayAlert(&#39;onError&#39;, JSON.stringify(e));<br>  };<br>  //Used to send back hash generated to SDK<br>  const sendBackHash = async (hashName, hashString) =&gt; {<br>    console.log(hashName);<br>    var hashValue = await generateResponseHash({hash: `${hashString}`});<br>    result = {[hashName]: hashValue?.data};<br>    PayUBizSdk.hashGenerated(result);<br>  };<br><br>  const generateHash = e =&gt; {<br>    console.log(e.hashName);<br>    console.log(e.hashString);<br>    sendBackHash(e?.hashName, e?.hashString);<br>  };<br><br>  const setActiveForm = () =&gt; {<br>    setSubmit(false);<br>    setIsFormVisible(true);<br>  };<br><br>  const payuCheckout = async () =&gt; {<br>    try {<br>      const createPaymentParams = () =&gt; {<br>        var txnid =<br>          &#39;&lt;Unique id : example - create an order and pass its primary key as String&gt;&#39;;<br>        var payUPaymentParams = {<br>          key: PAYU_KEY, //setup your config for processing .env variables in file<br>          transactionId: txnid,<br>          amount: totalprice?.toFixed(2),<br>          productInfo: &#39;&lt;INFO_PRODUCT&gt;&#39;,<br>          firstName: &#39;&lt;USERNAME&gt;&#39;,<br>          email: &#39;&lt;USER_EMAIL&gt;&#39;,<br>          phone: &#39;&lt;USER_CONTACT&gt;&#39;,<br>          android_surl: &#39;&lt;URL_TO_GO_AFTER_SUCCESS_PAYMENT&gt;&#39;,<br>          android_furl: &#39;&lt;URL_TO_GO_AFTER_FAILURE_PAYMENT&gt;&#39;,<br>          environment: &#39;0&#39;, //&#39;1&#39; for development, &#39;0&#39; for production make sure it is a string<br>          userCredential: `uid:${auth()?.currentUser?.uid}`,<br>        };<br><br>        var payUCheckoutProConfig = {<br>          primaryColor: &#39;#f2c585&#39;,<br>          secondaryColor: &#39;#0e5ca4&#39;,<br>          merchantName: &#39;&lt;MERCHANT_NAME&gt;&#39;,<br>          merchantLogo: &#39;&lt;MERCHANT_LOGO&gt;&#39;,<br>          showExitConfirmationOnCheckoutScreen:<br>            showExitConfirmationOnCheckoutScreen,<br>          showExitConfirmationOnPaymentScreen:<br>            showExitConfirmationOnPaymentScreen,<br>          cartDetails: cartDetails,<br>          paymentModesOrder: paymentModesOrder,<br>          surePayCount: surePayCount,<br>          merchantResponseTimeout: merchantResponseTimeout,<br>          autoSelectOtp: autoSelectOtp,<br>          // Android specific property<br>          autoApprove: autoApprove,<br>          merchantSMSPermission: merchantSMSPermission,<br>          showCbToolbar: showCbToolbar,<br>        };<br>        if (enforcePaymentEnable) {<br>          payUCheckoutProConfig[&#39;enforcePaymentList&#39;] = [<br>            {payment_type: &#39;NB&#39;},<br>            {payment_type: &#39;CARD&#39;},<br>          ];<br>        }<br><br>        return {<br>          payUPaymentParams: payUPaymentParams,<br>          payUCheckoutProConfig: payUCheckoutProConfig,<br>        };<br>      };<br><br>      console.log(&#39;Method launched amount =&#39; + totalprice);<br>      await PayUBizSdk.openCheckoutScreen(createPaymentParams());<br>    } catch (error) {<br>      console.log(&#39;Error during payment:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;TouchableOpacity<br>      style={shipstyle.buttoncheckout}<br>      onPress={e =&gt; payuCheckout()}&gt;<br>      &lt;Text style={shipstyle.buttontext}&gt;CHECKOUT&lt;/Text&gt;<br>    &lt;/TouchableOpacity&gt;<br>  );<br>};<br>export default Checkout;</pre><p>In the above code <em>generateResponseHash. </em>is the method that takes the hashString, appends the merchant salt to it, and then returns the SHA-51 2 encrypted hashData.</p><p>Calling the <em>generateResponseHash method </em>in my OrderState.js, below is the code snippet :</p><pre>let url = process.env.API_URL;<br><br> const generateResponseHash = async hash =&gt; {<br>    try {<br>      let res = await axios.post(`${url}/api/response/generatehashdata`, hash, {<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>      });<br> <br>      return res;<br>    } catch (err) {<br>      console.log(&#39;Hash Error:&#39;, err);<br>    }<br>  };</pre><p>As merchant salt is very confidential data, it should not be computed at the frontend. We’ll process the encryption at our server and return the value to our frontend. Below is the code for the same.</p><p>3. Update Node JS server code</p><pre>var jsSHA = require(&#39;jssha&#39;);<br>const express = require(&#39;express&#39;);<br>const router = express.Router();<br><br>router.post(&#39;/generatehashdata&#39;, urlencodedParser, async (req, res) =&gt; {<br>  // Generate new Hash<br>  var hashData = req.body.hash + process.env.SALT;<br>  var sha = new jsSHA(&#39;SHA-512&#39;, &#39;TEXT&#39;);<br>  sha.update(hashData);<br>  var hash = sha.getHash(&#39;HEX&#39;);<br><br>  res.json(hash);<br>});</pre><p>4. Test payments<br>Once you press CHECKOUT in your app, if everything is executed correctly, it should redirect you to the PayU payment Gateway.</p><p>Happy Coding ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c891293a3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to bulk upload data in mongoDB from our Excel file using RestAPI and multer?]]></title>
            <link>https://medium.com/@sabhya12.saini/how-to-bulk-upload-data-in-mongodb-from-our-excel-file-using-restapi-and-multer-3767b6151225?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3767b6151225</guid>
            <category><![CDATA[excel-data-entry]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[multer]]></category>
            <category><![CDATA[upload]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Sun, 25 Jun 2023 14:10:25 GMT</pubDate>
            <atom:updated>2023-06-25T14:10:25.044Z</atom:updated>
            <content:encoded><![CDATA[<p>As I delved into the realm of Full Stack MERN Development, I found myself working with limited data in MongoDB. However, my recent project has presented me with a valuable opportunity to explore a fascinating feature that has piqued my curiosity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-k_uuJtQk4EeTT5bxminPA.png" /><figcaption>NodeJS, ExpressJS, Multer and MongoDB to upload Excel file</figcaption></figure><p>Steps to follow :</p><ol><li>Add packages</li></ol><pre>yarn add multer convert-excel-to-json mongodb express mongoose mongodb</pre><p>2. Connect to MongoDB</p><p>One needs to create a database and collection in MongoDB by logging in. Once done, for connection of the database with our NodeJS application, we need to have a MongoURI : <br><em>mongodb+srv://&lt;user&gt;:&lt;password&gt;@&lt;cluster&gt;/&lt;database_name&gt;?retryWrites=true&amp;w=majority</em></p><p>Update this mongoURI in db.js file in your root directory of the project with the below code:</p><pre>const mongoose = require(&quot;mongoose&quot;);<br>const config = require(&quot;config&quot;);<br>const db = &quot;mongodb+srv://&lt;user&gt;:&lt;password&gt;@&lt;cluster&gt;/&lt;database_name&gt;?retryWrites=true&amp;w=majority&quot;; <br><br>const connectDB = async () =&gt; {<br>  try {<br>    await mongoose.connect(db, {<br>      useNewUrlParser: true,<br>      useCreateIndex: true,<br>      useFindAndModify: false,<br>      useUnifiedTopology: true,<br>    });<br><br>    console.log(&quot;MongoDB Connected...&quot;);<br>  } catch (err) {<br>    console.error(&quot;mongo eroor:&quot;, err.message);<br>    process.exit(1);<br>  }<br>};<br><br>module.exports = connectDB;</pre><p>3. Create a schema for the collection</p><pre>const mongoose = require(&quot;mongoose&quot;);<br><br>const ArtistSchema = mongoose.Schema(<br>  {<br>    speciality: {<br>      type: String,<br>    },<br>    about: {<br>      type: String,<br>    },<br>    name: {<br>      type: String,<br>      required: true,<br>    },<br>    artist_img: {<br>      type: String,<br>    },<br>    email: {<br>      type: String,<br>      unique: true,<br>    },<br>  },<br>  { timestamps: true }<br>);<br><br>module.exports = mongoose.model(&quot;artists&quot;, ArtistSchema);</pre><p>4. Create an excel sheet with the name as ‘artist’ and save the file as ‘artist’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwfS1-lMSoviGHomBEvirg.png" /></figure><p>5. Update the server.js / App.js / Index.js (Root file of the NodeJS project)</p><pre>const express = require(&quot;express&quot;);<br>const connectDB = require(&quot;./config/db&quot;);<br>const mongoDB = require(&quot;mongodb&quot;);<br>const MongoClient = require(&quot;mongodb&quot;).MongoClient;<br>const config = require(&quot;config&quot;);<br>const excelToJson = require(&quot;convert-excel-to-json&quot;);<br>const fs = require(&quot;fs&quot;);<br><br>let url = &quot;mongodb+srv://&lt;user&gt;:&lt;password&gt;@&lt;cluster&gt;/&lt;database_name&gt;?retryWrites=true&amp;w=majority&quot;;<br><br>cloudinary.config({<br>  cloud_name: process.env.REACT_APP_CLOUD_NAME,<br>  api_key: process.env.REACT_APP_API_KEY,<br>  api_secret: process.env.REACT_APP_API_SECRET,<br>});<br>global._basedir = __dirname;<br>require(&quot;dotenv&quot;).config();<br><br>const cors = require(&quot;cors&quot;);<br>const multer = require(&quot;multer&quot;);<br><br>const app = express();<br><br>app.use(bodyParser.urlencoded({ extended: true }));<br><br>// Connect Database<br>connectDB();<br><br>const storage = multer.diskStorage({<br>  destination: (req, file, cb) =&gt; {<br>    cb(null, path.join(_basedir, &quot;uploads&quot;));<br>  },<br>  filename: (req, file, cb) =&gt; {<br>    cb(null, file.originalname);<br>  },<br>});<br><br>const upload = multer({ storage: storage });<br><br>// Express upload REST API<br>app.post(&quot;/api/uploadfile&quot;, upload.single(&quot;uploadfile&quot;), (req, res) =&gt; {<br>  try {<br>    const filePath = req.file;<br>    importExcelData2MongoDB(filePath);<br>    res.json({<br>      msg: &quot;File Uploaded&quot;,<br>      file: req.file?.filename,<br>    });<br>  } catch (err) {<br>    console.log(&quot;Error uploading file:&quot;, err);<br>    res.status(500).json({ error: &quot;Failed to upload file&quot; });<br>  }<br>});<br><br>// Import to MongoDB<br>async function importExcelData2MongoDB(filePath) {<br>  try {<br>    const excelData = await excelToJson({<br>      sourceFile: filePath?.path,<br>      sheets: [<br>        {<br>          name: filePath.filename.split(&quot;.&quot;)[0],<br>          header: {<br>            rows: 1, // no/s. of the row that has headers in your excel sheet<br>          },<br>          columnToKey: {<br>            A: &quot;speciality&quot;, //these attributes should be similar to the ones in your excel file<br>            B: &quot;about&quot;,<br>            C: &quot;name&quot;,<br>            D: &quot;artist_img&quot;,<br>            E: &quot;email&quot;,<br>          },<br>        },<br>      ],<br>    });<br><br>    const sheetName = filePath.filename.split(&quot;.&quot;)[0]; // Update the sheet name<br><br>    if (!excelData[sheetName] || excelData[sheetName].length === 0) {<br>      throw new Error(`No data found in the &#39;${sheetName}&#39; sheet.`);<br>    } else {<br>      const client = await MongoClient.connect(url, { useNewUrlParser: true });<br>      console.log(&quot;Connected to MongoDB&quot;);<br><br>      const db = client.db(&quot;&lt;database_name&gt;&quot;);<br>      const collection = db.collection(&quot;&lt;collection_name&gt;&quot;);<br><br>      const result = await collection.insertMany(excelData[sheetName]);<br>      console.log(&quot;Number of documents inserted:&quot;, result.insertedCount);<br><br>      client.close();<br>      fs.unlinkSync(filePath?.path);<br>    }<br>  } catch (err) {<br>    console.log(&quot;Error importing data to MongoDB:&quot;, err);<br>    throw err;<br>  }<br>}<br><br>// Middleware<br>app.use(express.json({ limit: &quot;50mb&quot; }));<br><br>// Serve static assets in production<br>if (process.env.NODE_ENV === &quot;production&quot;) {<br>  // Set static folder<br>  app.use(express.static(&quot;client/build&quot;));<br>  app.use(express.static(&quot;public&quot;));<br><br>  app.get(&quot;*&quot;, (req, res) =&gt;<br>    res.sendFile(path.resolve(__dirname, &quot;client&quot;, &quot;build&quot;, &quot;index.html&quot;))<br>  );<br>}<br><br>const PORT = process.env.PORT || 8080;<br><br>app.listen(PORT, () =&gt; console.log(`Server started on port ${PORT}`));</pre><p>6. Create a folder named as ‘uploads’ where the uploaded files will go, in your project’s root directory.</p><p>7. Test the API using Postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycqgdihLmRDqNHlenqwsEQ.png" /><figcaption>postman testing of the API for bulk uploading excel data in MongoDB</figcaption></figure><p>Make sure that the key has the type selected as ‘file’ where the key has value as — uploadfile.<br>Once you press that bright blue “send” button on postman, if the code is correct and your excel sheet is configured correctly, you should get the response message as -<br> {msg: “File Uploaded”,<br> file: &lt;filename&gt;}<br>and a new file added inside your “uploads” folder. Once you have observed this, go to mongoDB and check for the new added files in your respective database’s collection.</p><p>Hoping it helps you complete that bulk upload in few minutes! <br>Happy Coding ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3767b6151225" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Chat feature using React JS, MongoDB Realm and Node JS]]></title>
            <link>https://medium.com/@sabhya12.saini/creating-chat-feature-using-react-js-mongodb-realm-and-node-js-d8b61292742c?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b61292742c</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[mongodb-realm]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[chat]]></category>
            <category><![CDATA[realm]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 16:54:30 GMT</pubDate>
            <atom:updated>2023-06-11T16:54:30.607Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWpNzSpEdrp1zN0EMt7OWQ.jpeg" /><figcaption><a href="https://unblast.com/group-chat-illustration-ai/">https://unblast.com/group-chat-illustration-ai/</a></figcaption></figure><p>To create a React app with a Node.js server that uses MongoDB Realm to create a chat feature, you’ll need to follow following steps. Here’s a general high-level overview of the process:</p><h4>1. Set up the MongoDB Realm application:</h4><p>— Sign up for a MongoDB Atlas account if you don’t have one already.<br> — Create a new MongoDB Realm application within your Atlas account.<br> — Set up a MongoDB collection to store chat messages.<br> — <a href="https://rb.gy/ty4lu">Link to get you started with MongoDb Atlas</a></p><h4>2. Set up the Node.js server:</h4><p>— Create a new directory for your server.<br> — Initialize a new Node.js project using npm or yarn.<br> — Install necessary dependencies, such as `express`, `mongoose`, and `realm-web`.</p><pre>yarn add express mongoose realm-web</pre><h4>3. Create a backend API:</h4><p>— Set up an Express server to handle API requests.<br> — Connect to your MongoDB Realm application using the `relam-web` library.<br> — Create API endpoints to handle chat-related operations, such as sending and retrieving messages.</p><p>Create model for the ChatSchema:</p><pre>const mongoose = require(&#39;mongoose&#39;);<br><br>const ChatSchema = mongoose.Schema(<br>  {<br>    sender: { type: String, required: true },<br>    message: { type: String, required: true },<br>    receiver: { type: String, required: true },<br>    timestamp: { type: Date, default: Date.now } // Custom timestamp field<br>  }<br>);<br><br>module.exports = mongoose.model(&#39;chats&#39;, ChatSchema);</pre><p>Update the code in your root file for the server, server.js/ index.js/ app.js file :</p><pre>const express = require(&#39;express&#39;);<br>const connectDB = require(&#39;./config/db&#39;);<br>const path = require(&#39;path&#39;);<br>var bodyParser = require(&#39;body-parser&#39;);<br>const fileUpload = require(&#39;express-fileupload&#39;);<br>const {App, Credentials} = require(&#39;realm-web&#39;);<br><br>require(&#39;dotenv&#39;).config();<br><br>var cors = require(&#39;cors&#39;);<br><br>const app = express();<br>app.use(fileUpload({useTempFiles: true}));<br>app.use(<br>  cors({<br>    origin: <br>      &#39;http://localhost:3000&#39;<br>  })<br>);<br><br><br>app.use(bodyParser.urlencoded({extended: true}));<br><br>// Connect Database<br>connectDB();<br><br>// Connect to MongoDB Realm<br>const REALM_APP_ID = &#39;&lt;your_realm_app_id&gt;&#39;;<br>const appRealm = new App({id: REALM_APP_ID});<br><br>// Init Middleware<br>app.use(express.json({limit: &#39;50mb&#39;}));<br>app.use(express.urlencoded({limit: &#39;50mb&#39;, extended: true}));<br>app.use(cors());<br><br>async function authenticateUser() {<br>  try {<br>    const user = await appRealm.logIn(Credentials.anonymous()); // Authenticate anonymously<br><br>    if (!user) {<br>      console.log(&#39;Failed to authenticate user&#39;);<br>    }<br><br>    return user?.mongoClient(&#39;mongodb-atlas&#39;);<br>  } catch (error) {<br>    console.log(&#39;Authentication error:&#39;, error);<br>    throw error;<br>  }<br>}<br><br>app.post(&#39;/api/realm-messages&#39;, async (req, res) =&gt; {<br>  try {<br>    const {sender, message, receiver} = req.body;<br>    const newMessage = {sender, message, receiver};<br><br>    const mongodb = await authenticateUser();<br><br>    if (!mongodb) {<br>      throw new Error(&#39;Failed to authenticate MongoDB client&#39;);<br>    }<br><br>    const chatCollection = mongodb.db(&#39;&lt;your_mongodb_database_name&gt;&#39;).collection(&#39;&lt;mongodb_collection_name&gt;&#39;);<br><br>    const result = await chatCollection.insertOne(newMessage);<br>    res.status(201).json(result);<br>  } catch (error) {<br>    console.log(&#39;Message sending error:&#39;, error);<br>    res.status(500).json({error: &#39;Failed to send message&#39;});<br>  }<br>});<br><br>// Retrieve all chat messages<br>app.get(&#39;/api/messages&#39;, async (req, res) =&gt; {<br>  try {<br>    const messages = await ChatMessage.find().sort({timestamp: &#39;asc&#39;});<br>    res.json(messages);<br>  } catch (error) {<br>    res.status(500).json({error: &#39;Failed to retrieve messages&#39;});<br>  }<br>});<br>module.exports = router;<br>const PORT = process.env.PORT || 8080;<br><br>app.listen(PORT, () =&gt; console.log(`Server started on port ${PORT}`));</pre><h4>4. Set up the React app:</h4><p>— Create a new directory for your React app.<br> — Initialize a new React project using Create React App or any other method you prefer.<br> — Install necessary dependencies, such as `axios` for making API requests.</p><pre>yarn add axios</pre><h4>5. Build the chat user interface:</h4><p>— Create React components to handle the chat user interface, such as a message input field and a message list.<br> — Use `axios` to make API requests to the backend server for sending and retrieving messages.<br> — Update the UI in real-time as new messages are sent or received.</p><p>Add this code for hitting the backend API endpoint to add and retrieve messages from the database :</p><pre><br>const url=&lt;url_where_backend_is_hosted&gt; //(example: http://localhost:8080)<br>//Get Chats<br>const getChats = async () =&gt; {<br>    try {<br>      const res = await axios.get(`${url}/api/messages`);<br>      dispatch({<br>        type: GET_CHATS,<br>        payload: res?.data,<br>      });<br>    } catch (err) {<br>      // console.log(&quot;err&quot;, err);<br>      dispatch({<br>        type: CHAT_ERROR,<br>        payload: err?.response?.msg,<br>      });<br>    }<br>  };<br> // Add Chat<br>  const addChat = async (chat) =&gt; {<br>    const config = {<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      },<br>    };<br>    try {<br>      const res = await axios.post(`${url}/api/realm-messages`, chat, config);<br><br>      dispatch({<br>        type: ADD_CHAT,<br>        payload: res.data,<br>      });<br>    } catch (err) {<br>      dispatch({<br>        type: CHAT_ERROR,<br>        payload: err?.response?.msg,<br>      });<br>    }<br>  };</pre><p>Add a file named Chat.js in React App:</p><pre>import React, { useState, useEffect, useContext } from &quot;react&quot;;<br>import { getAuth } from &quot;firebase/auth&quot;;<br>import SendIcon from &quot;@mui/icons-material/Send&quot;;<br>import ChatContext from &quot;../../context/chat/chatContext&quot;;<br>import CardMedia from &quot;@mui/material/CardMedia&quot;;<br><br>const Chat = () =&gt; {<br>  const chatContext = useContext(ChatContext);<br>  const { getChats, chats, addChat } = chatContext;<br>  const [chatMessage, setChatMessage] = useState(&quot;&quot;);<br>  const appId = process.env.REACT_APP_APP_ID; // Replace with your MongoDB Stitch app ID<br>  const appName = process.env.REACT_APP_APP_NAME; // Replace with your named app&#39;s name<br>  const auth = getAuth();<br><br>  const sendMessage = async () =&gt; {<br>    await addChat({<br>      sender: &lt;sender_id&gt;,<br>      message: chatMessage,<br>      receiver: &lt;reciever_id&gt;,<br>    });<br>    setChatMessage(&quot;&quot;); // Clear the input field after sending the message<br>  };<br><br>  useEffect(() =&gt; {<br>    getChats();<br>  }, [auth, chats?.length]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Chat&lt;/h1&gt;<br>      &lt;div className=&quot;chat-container&quot;&gt;<br>        {chats?.map((message) =&gt; (<br>          &lt;div<br>            key={message?._id}<br>            className={`chat-message ${<br>              message?.sender === auth?.currentUser?.uid ? &quot;sent&quot; : &quot;received&quot;<br>            }`}<br>          &gt;<br>            &lt;span className=&quot;message&quot;&gt;{message?.message}&lt;/span&gt;<br>            &lt;span className=&quot;metadata&quot;&gt;{message?.createdAt}&lt;/span&gt;<br>          &lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>      &lt;div className=&quot;input-container&quot;&gt;<br>        &lt;input<br>          label=&quot;message&quot;<br>          type=&quot;text&quot;<br>          placeholder=&quot;Enter message&quot;<br>          name=&quot;name&quot;<br>          onChange={(e) =&gt; setChatMessage(e.target.value)}<br>          required={true}<br>        /&gt;<br>        &lt;button onClick={sendMessage}&gt;<br>          &lt;SendIcon /&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Chat;</pre><p>CSS code :</p><pre>/* Chat Container */<br>.chat-container {<br>  display: flex;<br>  flex-direction: column;<br>  overflow-y: scroll;<br>  height: 500px; /* Adjust the height as needed */<br>  padding: 10px;<br>}<br><br>/* Chat Message */<br>.chat-message {<br>  display: flex;<br>  flex-direction: column;<br>  align-items: flex-start;<br>  margin-bottom: 10px;<br>}<br><br>.chat-message.sent {<br>  align-items: flex-end;<br>}<br><br>.chat-message .message {<br>  background-color: #DCF8C6; /* Color for sent messages */<br>  color: black;<br>  padding: 10px;<br>  border-radius: 10px;<br>}<br><br>.chat-message.sent .message {<br>  background-color: #E1FFC7; /* Color for received messages */<br>}<br><br>.chat-message .metadata {<br>  font-size: 12px;<br>  color: #888;<br>}<br><br>/* Input Container */<br>.input-container {<br>  display: flex;<br>  align-items: center;<br>  padding: 10px;<br>  border-top: 1px solid #ddd;<br>}<br><br>.input-container input {<br>  flex-grow: 1;<br>  padding: 10px;<br>  border: none;<br>  border-radius: 5px;<br>  margin-right: 10px;<br>}<br><br>.input-container button {<br>  border: none;<br>  background: transparent;<br>  cursor: pointer;<br>  outline: none;<br>}</pre><h4>6. Connect the React app with the Node.js server:</h4><p>— Ensure that your Node.js server is running and accessible.<br> — Modify the React app’s API requests to use the appropriate server URL and endpoints.</p><h4>7. Test and deploy:</h4><p>— Test your application locally to ensure everything is working as expected.<br> — Deploy your React app and Node.js server to a hosting platform of your choice.<br> — Configure any necessary environment variables or settings for the production environment.</p><p>Happy Coding! ✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b61292742c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Poem on Anxiety of a Taurus]]></title>
            <link>https://medium.com/@sabhya12.saini/poem-on-anxiety-of-a-taurus-4fd43711b35?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fd43711b35</guid>
            <category><![CDATA[taurus]]></category>
            <category><![CDATA[anxiety]]></category>
            <category><![CDATA[poem]]></category>
            <category><![CDATA[mental-health]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Thu, 25 May 2023 08:11:03 GMT</pubDate>
            <atom:updated>2023-05-25T08:11:03.527Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to mental health awareness month! Here is a small poem I have written around anxiety when I last experienced it overwhelmingly, and that was a week ago.</p><p>Context : Despite of me going to the mountains, trekking and painting after a tumultuous break from career, I still felt the anxiety and that to me has become so normal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ryYJ0007JuPrkzxcYUSVIw.jpeg" /><figcaption>Artwork by Sabhya Saini</figcaption></figure><p>Since morning,<br>Anxiety has my heart racing,<br>Racing my mind to<br>Question the existence of all that is,<br>Of all that I am<br>Of all that I can be.<br>Time is saying<br>Enough of the struggles<br>And now the abundance<br>Is at the doorstep,<br>And my gut approves.<br>Yet there is so much uncertainty<br>That<br>Since morning<br>Anxiety has my heart racing.<br>Racing the heart of a Taurus,<br>The Bull,<br>Who except stability and peace gets<br>Offended by the uncertainty!</p><p>- Sabhya Saini<br><a href="https://www.instagram.com/explore/tags/sabhyasaini/">#sabhyasaini</a> <a href="https://www.instagram.com/explore/tags/theperception/">#theperception</a> <a href="https://www.instagram.com/explore/tags/words/">#words</a> <a href="https://www.instagram.com/explore/tags/taurus/">#taurus</a> #poem</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fd43711b35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enabling cookies in React JS]]></title>
            <link>https://medium.com/@sabhya12.saini/enabling-cookies-in-react-js-10c631219579?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c631219579</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[ipaddressstatic]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[cookies]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 13:28:39 GMT</pubDate>
            <atom:updated>2023-04-22T13:41:31.511Z</atom:updated>
            <content:encoded><![CDATA[<p>A mature, responsible and accountable way of managing data is to know the identity of the user that has registered their data on the database of the service provider, and also let the user know of the same. <br>Concept of cookies help us do it, without making the user do additional effort while using the product or the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*wOrkZQRL_VNeEIl2e13sKQ.jpeg" /><figcaption>Reference : <a href="https://ophtek.com/how-do-cookies-affect-your-cyber-security/">https://ophtek.com/how-do-cookies-affect-your-cyber-security/</a></figcaption></figure><h3>What is cookie on internet ?</h3><p><em>A cookie is information that a website puts on a user’s computer. Cookies store limited information from a web browser session on a given website that can then be retrieved in the future. They are also sometimes referred to as browser cookies, web cookies or internet cookies.</em></p><p>If you are someone who is familiar with Async Storage in React Native, cookies provide the same support in React JS. The value is stored in a key-value pair.</p><h3>Why is it needed ?</h3><p>The use case I am elaborating on here is based on e-commerce. User journey:<br>- User lands on the landing screen<br>- Likes something and adds it to their cart<br>So far so good! I being a business, would like to have further info when the user finally decides to make a purchase and send me an order. I would have to authorise them to do so. <br>- User authorise themselves on my platform<br>The problem is, how will I know what products they had stored in their cart earlier?<br>Thus, I need to find something from the user’s browser that is unique, that I can store in a cookie, and once authorisation is complete, based on the unique key, I’ll transfer the data to the authorised key.</p><h4>What can be that unique key? : IP Address</h4><p>IP Address : An Internet Protocol (IP) address is a unique numerical identifier for every device or network that connects to the internet.</p><h3>Integrating Cookies in my website</h3><ol><li>Install package ‘react-cookie’</li></ol><pre>yarn add react-cookie-consent</pre><p>2. Update your landing screen code :</p><pre>import CookieConsent, { Cookies } from &quot;react-cookie-consent&quot;; <br><br>const LandingScreen = () =&gt; {<br><br>  const [useridip, setUseridip] = useState();<br><br>  const AcceptCookie = async () =&gt; {<br>    await Cookies.set(&quot;userip&quot;, useridip, { path: &quot;/&quot; }); // &quot;userip&quot; is the key corresponding to which value is stored, here the value is stored in the variable &#39;userid&#39;<br>  };<br><br>  useEffect(() =&gt; {<br>   getIP();<br>  }, []);<br><br>  return (<br>        &lt;CookieConsent<br>        debug={true} //remove in production<br>        extraCookieOptions={{ domain: &quot;yourdomainname.com&quot; }}<br>        onAccept={() =&gt; AcceptCookie()}<br>        style={{ background: &quot;#f1f2f1&quot;, color: &quot;black&quot; }}<br>        buttonStyle={{ backgroundColor:&#39;#0c3059&#39;,color: &quot;white&quot;, fontSize: &quot;13px&quot; }}<br>        buttonText=&quot;OKAY!&quot;<br>        // expires={150}<br>      &gt;<br>        We use cookies to ensure you have the best browsing experience on our<br>        website.<br>      &lt;/CookieConsent&gt;<br>  );<br>}<br><br>export default LandingScreen;</pre><p>3. When the user adds the product to the cart, a reference id for the cookie should be passed that has the value stored in a key for the IP Address.</p><pre>import axios from &quot;axios&quot;;<br><br>const getUserIp = async () =&gt; {<br>    let res;<br>    res = await axios.get(&quot;https://api.ipify.org/?format=json&quot;);<br>    await setUseridip(res.data.ip);<br>  };</pre><p>4. To pass the value of the cookie, we need to retrieve it :</p><pre>import CookieConsent, {Cookies} from &quot;react-cookie-consent&quot;;<br><br>let ip = Cookies.get(&quot;userip&quot;);</pre><p>That is how we have stored IP address of the user in the cookie.</p><p><em>I faced CORS error while performing this feature. Thus mentioning the solution for the same :<br> </em><br>1. Update your frontend’s package.json file to incorporate a proxy.</p><pre>{<br>  &quot;name&quot;: &quot;app-name&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;dependencies&quot;: {<br>  },<br>  &quot;scripts&quot;: {<br>  },<br>  &quot;engines&quot;: {<br>  },<br>  &quot;browserslist&quot;: {<br>    &quot;production&quot;: [<br>      &quot;&gt;0.2%&quot;,<br>      &quot;not dead&quot;,<br>      &quot;not op_mini all&quot;,<br>      &quot;&gt;0.3%&quot;,<br>      &quot;not ie 11&quot;,<br>      &quot;not dead&quot;<br>    ],<br>    &quot;development&quot;: [<br>      &quot;last 1 chrome version&quot;,<br>      &quot;last 1 firefox version&quot;,<br>      &quot;last 1 safari version&quot;<br>    ]<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;cross-env&quot;: &quot;^7.0.3&quot;,<br>    &quot;dotenv&quot;: &quot;^16.0.3&quot;<br>  },<br>  &quot;proxy&quot;: &quot;&lt;your_server_url&gt;&quot; // add this line<br>}</pre><p>2. Update server code. The main file : server.js/ app.js/ index.js should have these line of code :</p><pre>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const app = express();<br><br>app.use(cors({ origin: &#39;&lt;your_frontend_url&gt;&#39; }));</pre><p>I hope this helps you out in your journey of integrating cookies! Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c631219579" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Presenting data in slices in React Native]]></title>
            <link>https://medium.com/@sabhya12.saini/presenting-data-in-slices-in-react-native-c19c11dbde3c?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c19c11dbde3c</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[slicing-software]]></category>
            <category><![CDATA[flatlist]]></category>
            <category><![CDATA[useref]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 06:00:19 GMT</pubDate>
            <atom:updated>2023-04-08T06:00:19.903Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine yourself at a kid’s birthday party, where every guest is excited, overwhelmed and waiting for that cake! <br>When do you think the feeling of excitement and overwhelmingness transcends into euphoria?</p><p>On an e-commerce platform that cake is presented to it’s guests in multiple forms and quantities all at the same time. The cake is the personification of lust. Every product on the platform is trying to attract the user.</p><p>Earlier that attraction effort was made through images and texts, now in today’s time it is done through videos and music. Let’s imagine a platform where every video is playing simultaneously on the screen.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F5233455&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Ffrustrated-frustrating-ugh-annoyed-crazy-gif-5233455&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fo-w5uMJDCjgAAAAC%2Ffrustrated-frustrating.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d05d8d7d1b3df340530dbc02fb94503/href">https://medium.com/media/5d05d8d7d1b3df340530dbc02fb94503/href</a></iframe><h3>That is WHY SLICING !</h3><p>Because we have so much of data in the same format, we can leverage list and an optimised list in React Native is <strong>Flatlist</strong>.</p><p>Flatlist accepts the data to render elements inside it, we need to manage this data being sent. When the first batch of items are completely exhausted and end is reached, we need to send the new data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*T8_b0yWxOCOJffaw6WUhhg.png" /></figure><p>Once the end is reached and footer is invoked, we are calling the method updateBatch. Here is the code for the same :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*UP-hpYlErP-_C0DeSOVaXA.png" /></figure><p>This method updates the batch start and end values, pass it to another method named getBatchProducts, which then returns the sliced items from the entire list of products that we have.</p><p>It is a good practice to present data to your user in a sliced manner for better and efficient goal completion.</p><h3>Enhancing UI for certain index of the Flatlist Item</h3><p>Now if you are working with video, at a certain instance, only one should be playing and rest should be either muted or paused. Now how to achieve that?</p><h4>Using UseRef from React</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*mvh_NOCpiO6-DX57WtoW5A.png" /></figure><p>By leveraging onViewableItemsChanged and ViewabilityConfig props of Flatlist, we can identify which item is viewable on the screen and which is not. Based on that value you can update the UI of the component called inside renderItem method. For correct viewability configuration one also needs to use the prop getItemLayout.</p><h3>Euphoria</h3><p>Once the user is able to see the items one moment at a time, they can make decisions consciously and clearly because so much of the noise in the background is minimised. Once that happens, they can get the product that they want and the effort of smart attraction from the company is also justified as the goal is achieved for both the collaborators, i.e user and the company.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c19c11dbde3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to upload image on Google Cloud Storage using React Native with TypeScript, Node JS and Multer?]]></title>
            <link>https://medium.com/@sabhya12.saini/how-to-upload-image-on-google-cloud-storage-using-react-native-with-typescript-node-js-and-multer-eedc34a05fd6?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eedc34a05fd6</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[image-upload]]></category>
            <category><![CDATA[upload-on-google]]></category>
            <category><![CDATA[multer]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 16:17:48 GMT</pubDate>
            <atom:updated>2022-11-22T16:17:48.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXSBO0GePWwnwZbyWK9j4Q.png" /></figure><p>Uploading image can be a complicated task. I earlier worked with Cloudinary image upload API, but then we surpassed it’s limit of free usage. As the organisation was already using some services of Google Cloud Platform(GCP), this turned out to be a smart option to switch to.</p><h3>Google Cloud Storage Tasks</h3><ol><li>Create a <strong>bucket</strong> and <strong>service account</strong> on GCP. <br>Follow this link : <a href="https://www.bezkoder.com/google-cloud-storage-free/">https://www.bezkoder.com/google-cloud-storage-free/</a></li><li>Once you get the key, save it with the name : <strong><em>google-cloud-key.json</em></strong></li></ol><h3>Node JS Tasks</h3><ol><li>Create a React JS App: <a href="https://reactjs.org/docs/create-a-new-react-app.html">https://reactjs.org/docs/create-a-new-react-app.html</a><br>npx create-react-app &lt;your-app-name&gt;</li><li>Bring the <strong><em>google-cloud-key.json </em></strong>into the root directory of your project.</li><li>Add the following packages in your app using yarn or npm :</li></ol><pre>yarn install express express-fileupload dotenv multer @google-cloud/storage body-parser</pre><p>3. Update the index.js file with the following code:</p><pre>const express = require(&#39;express&#39;);<br>const fileUpload = require(&#39;express-fileupload&#39;);<br>require(&#39;dotenv&#39;).config();<br>var Multer = require(&#39;multer&#39;);<br>const util = require(&#39;util&#39;);<br>const { format } = require(&#39;util&#39;);<br>const { Storage } = require(&#39;@google-cloud/storage&#39;);<br>// Instantiate a storage client with credentials<br>const storage = new Storage({ keyFilename: &#39;google-cloud-key.json&#39; });<br>const bucket = storage.bucket(&#39;&lt;your-bucket-name&gt;&#39;);<br>const bodyParser = require(&#39;body-parser&#39;);<br><br><br>var cors = require(&#39;cors&#39;);<br><br>const app = express();<br>const maxSize = 2 * 1024 * 1024;<br><br>app.use(fileUpload());<br><br><br>app.use(express.json({ limit: &#39;50mb&#39; }));<br>app.use(express.urlencoded({ limit: &#39;50mb&#39;, extended: true }));<br>app.use(bodyParser.json());<br>app.use(bodyParser.urlencoded({ extended: false }));<br>app.use(cors());<br><br>//upload api on google cloud storage<br><br>app.post(&#39;/api/upload&#39;, async (req, res) =&gt; {<br> let tmpPath = req?.files;<br><br> try {<br>  await util.promisify(<br>   Multer({<br>    storage: Multer.memoryStorage(),<br>    limits: { fileSize: maxSize },<br>   }).single(&#39;file&#39;)<br>  );<br><br>  if (!tmpPath.file) {<br>   return res.status(400).send({ message: &#39;Please upload a file!&#39; });<br>  }<br><br>  // Create a new blob in the bucket and upload the file data.<br>  const blob = bucket.file(tmpPath.file.name);<br>  const blobStream = blob.createWriteStream({<br>   resumable: false,<br>  });<br><br>  blobStream.on(&#39;error&#39;, (err) =&gt; {<br>   console.log(&#39;blob error:&#39;, err);<br>   res.status(600).send({ message: err.message });<br>  });<br><br>  blobStream.on(&#39;finish&#39;, async (data) =&gt; {<br>   // Create URL for directly file access via HTTP.<br><br>   const publicUrl = format(<br>    `https://storage.googleapis.com/${bucket.name}/${blob.name}`<br>   );<br><br>   try {<br>    // Make the file public<br>    await bucket.file(tmpPath.file.name).makePublic();<br>   } catch {<br>    return res.status(500).send({<br>     message: `Uploaded the file successfully: ${tmpPath.file.name}, but public access is denied!`,<br>     url: publicUrl,<br>    });<br>   }<br><br>   res.status(200).send({<br>    message: &#39;Uploaded the file successfully: &#39; + tmpPath.file.name,<br>    url: publicUrl,<br>   });<br>  });<br><br>  blobStream.end(Buffer.from(tmpPath.file.data));<br> } catch (err) {<br>  if (err.code == maxSize) {<br>   return res.status(500).send({<br>    message: &#39;File size cannot be larger than 2MB!&#39;,<br>   });<br>  } else {<br>   res.status(500).send({<br>    message: `Could not upload the file: ${req.body.name}. ${err}`,<br>   });<br>  }<br> }<br>});<br><br>const PORT = process.env.PORT || 8080;<br><br>app.listen(PORT, () =&gt; console.log(`Server started on port ${PORT}`));</pre><h3>React Native Tasks</h3><ol><li>Create React Native App :</li></ol><pre>npx react-native init &lt;Your-app-name&gt; - template react-native-template-typescript</pre><p>2. Add packages to your app :</p><pre>yarn install react-native-axios react-native-vector-icons/FontAwesome react-native-image-crop-picker</pre><p>3. Add a new file UploadImage.tsx and import and call it inside App.tsx. Here is the code for UploadImage.tsx:</p><pre>import React, {useState} from &#39;react&#39;;<br>import {Text, View,ImageBackground, TouchableOpacity} from &#39;react-native&#39;;<br>import ImagePicker from &#39;react-native-image-crop-picker&#39;;<br>import axios from &#39;react-native-axios&#39;;<br>import Icon from &#39;react-native-vector-icons/FontAwesome&#39;;<br><br>export default function UploadImage() {<br>  const [image_url, setImage] = useState(&#39;&#39;);<br>  let url = process.env.API_URL;<br><br>  //function extracting filename of image from the path extracted by takePhoto function<br>  const extractFilename = path =&gt; {<br>    const pathArray = path.split(&#39;/&#39;);<br>    const lastIndex = pathArray.length - 1;<br>    return pathArray[lastIndex];<br>  };<br><br>  const takePhoto = () =&gt; {<br>    ImagePicker.openPicker({<br>      width: 300,<br>      height: 400,<br>      cropping: true,<br>      includeBase64: true,<br>    }).then(image =&gt; {<br>      var uri = image.path;<br>      var name = extractFilename(image.path);<br>      var type = image.mime;<br>      const source = {<br>        uri,<br>        type,<br>        name,<br>      };<br>      onUploadPhoto(source);<br>    });<br>  };<br><br>  const onUploadPhoto = async photo =&gt; {<br>    const formData = new FormData();<br>    formData.append(&#39;file&#39;, photo);<br>    try {<br>      let res = await axios.post(`${url}/api/upload`, formData, {<br>        headers: {&#39;Content-Type&#39;: &#39;multipart/form-data&#39;},<br>      });<br>      await setImage(res.data.url);<br>    } catch (err) {<br>      console.log(err);<br>    }<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;Text style={{fontSize: 12, alignSelf: &#39;auto&#39;}}&gt;Add a photo&lt;/Text&gt;<br>      &lt;TouchableOpacity onPress={takePhoto}&gt;<br>        &lt;Icon<br>          size={20}<br>          name=&quot;image&quot;<br>          color=&quot;white&quot;<br>          style={{marginBottom: -3, alignSelf: &#39;flex-end&#39;}}<br>        /&gt;<br>        &lt;View<br>          style={{<br>            backgroundColor: &#39;transparent&#39;,<br>            justifyContent: &#39;center&#39;,<br>            paddingLeft: &#39;29%&#39;,<br>          }}&gt;<br>          {image_url?.length !== 0 ? (<br>            &lt;ImageBackground<br>              source={{uri: image_url}}<br>              style={{height: 70, width: 70, alignSelf: &#39;flex-end&#39;}}<br>              imageStyle={{borderRadius: 2}}&gt;&lt;/ImageBackground&gt;<br>          ) : null}<br>        &lt;/View&gt;<br>      &lt;/TouchableOpacity&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>And with this you are done! All the best executing this!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eedc34a05fd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading images to Cloudinary through the server using multer in a MERN stack app]]></title>
            <link>https://medium.com/@sabhya12.saini/uploading-images-to-cloudinary-through-the-server-using-multer-in-a-mern-stack-web-app-356019e51c9c?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/356019e51c9c</guid>
            <category><![CDATA[multer]]></category>
            <category><![CDATA[mern-stack-developer]]></category>
            <category><![CDATA[cloudinary]]></category>
            <category><![CDATA[image-upload]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 17:17:12 GMT</pubDate>
            <atom:updated>2023-02-08T04:51:42.595Z</atom:updated>
            <content:encoded><![CDATA[<p>Uploading images locally in a MERN app can be easy, but that only uploads images on our local machine. If one wishes to deploy the application on a platform such as Netlify, one needs to take advantage of image hosting third-party applications. I have chosen Cloudinary, as it provides 25GB of free storage.</p><h4>What are we aiming at?</h4><ul><li>Uploading an image to our Cloudinary account using API. Using public_id to make sure only a single upload happens on the Cloudinary, even if several attempts of uploading a single image have been made.</li><li>Adding the web URL of the uploaded image into MongoDB Atlas Database.</li><li>Deleting the uploaded image on Cloudinary using API.</li><li>Deleting the added web URL of the uploaded image from our MongoDB database when the delete operation is performed from the frontend.</li></ul><h4>Pre-requisites:</h4><p>* Cloudinary account<br>* MongoDB account<br>* NPM installed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*QlSvhMWp08zPRm9YD4pnVA.png" /><figcaption>App structure</figcaption></figure><p>Once you have your Cloudinary account set up, add the following information in the .env file at the root directory :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*8fCAx9y6Rbf3tlsgoqPtWw.png" /></figure><h4><strong>server.js</strong></h4><p>Using multer storage in the server code. Add this code to server.js file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*T5ESHPcN14whPbIzbtFZUw.png" /></figure><p>Install dotenv npm package for your server, to use environment variables defined in the .env file :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*FgLXEHBaAgWHCQ2IG0Astg.png" /></figure><p>Configure Cloudinary credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*yjeAmlgWmgvdySKoUJm9Iw.png" /></figure><p>Install express-fileupload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*UTZbXB7wtzaq3c80U4ZQFA.png" /></figure><p>Install cors :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*WobLbQWMgbvBL0p-qUDong.png" /></figure><p>Import routes/controllers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*-iH7T-OlPi4pMLdxA2gM5Q.png" /></figure><p>API endpoint to upload the image on Cloudinary :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*FLf8JU50cMsWgY4wYqLv9g.png" /></figure><p>API endpoint to delete the image from Cloudinary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*OY_CXg2Nk_TpScZBDa5aQQ.png" /></figure><h4>Defining the Schema for MongoDB image URL tracking</h4><p><strong>Userimage.js</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*bhDoOsUIlgpJ3QFhVNUYLQ.png" /></figure><p><strong>Create API for CRUD operations on the Userimage model defined using Mongoose above.</strong></p><p><strong>Create actions using reducer for frontend in React JS and also the state.</strong></p><h4>Frontend Code in React JS or React Native</h4><p>OnSubmit method is called while submitting the selected image for upload :<br>Note : use <strong>react-native-axios</strong> package for React Native and <strong>axios </strong>package for React JS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*kBRABY216lZmJ4JP-EZxZA.png" /></figure><p>Calling the delete API endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*rQKjSG0nnzDiHeFc6H73QA.png" /></figure><p>UI of the application:</p><figure><img alt="UI of image upload template for Cloudinary" src="https://cdn-images-1.medium.com/max/1024/1*_zOZywpQQrf2YTIOJrzNGQ.png" /></figure><p>Source code available at: <a href="https://github.com/sbhaya/image-upload-cloudinary">https://github.com/sbhaya/image-upload-cloudinary</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=356019e51c9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Framer motion for card drag out animation]]></title>
            <link>https://medium.com/@sabhya12.saini/using-framer-motion-for-card-drag-out-animation-d63bbddd558e?source=rss-d94d5b1350b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d63bbddd558e</guid>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[framer-motion]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sabhya Saini]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 19:48:03 GMT</pubDate>
            <atom:updated>2021-08-27T19:48:03.152Z</atom:updated>
            <content:encoded><![CDATA[<p>I am new to coding UI animations and for this Figma design of mine, I traversed through CSS Animations, npm react-animations package but both of them didn’t work out for me and thus I landed upon Framer motion.</p><h3>What is Framer motion?</h3><p>It is a production-ready, open-source motion library for React. Well documented for beginners to start with. Despite the good documentation, I still struggled a bit initially to understand the concepts as I am completely new to Framer motion.</p><p><a href="https://www.framer.com/motion/">Motion - JavaScript &amp; React animation library</a></p><h3>What does it help with?</h3><ul><li>Spring animations</li><li>Simple keyframes syntax</li><li>Gestures (drag/tap/hover)</li><li>Layout and shared layout animations</li><li>SVG paths</li><li>Exit animations</li><li>Server-side rendering</li><li>Variants for orchestrating animations across components</li><li>CSS variables</li></ul><p>…and a whole lot more.</p><h3>What am I trying to implement with its help?</h3><figure><img alt="Drag out card animation in Framer animation using react." src="https://cdn-images-1.medium.com/max/700/1*R5H-TQ5O2mDgBBCSILvcUA.gif" /><figcaption>The animation was designed in Figma using artwork and handmade paper both created by me! Yes, I am multitalented this way and lockdown made me learn amazing things :)</figcaption></figure><h3>The execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*B83bYStE_tIJvaymm_XgFQ.png" /><figcaption>import statement</figcaption></figure><p>To be able to use framer one needs to import the framer-motion package using <strong>npm install framer-motion </strong>or <strong>yarn add framer-motion</strong></p><h4>Variants can come in handy to explicitly define the transitions and subcategorize them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*oSB3-cabyCBaHxNqrwKRuQ.png" /><figcaption>Defining the variants for the transitions and states for one motion component</figcaption></figure><p>The <strong>&lt;motion.div&gt;</strong> helps one define the component for animation using Framer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*jpqxo7zIPhjLr6vD7EJ2yg.png" /><figcaption>With &lt;motion.div&gt; one can define the component for animation using Framer</figcaption></figure><h4>Source Code</h4><p><a href="https://github.com/sbhaya/animation_projects">GitHub - sbhaya/animation_projects: Learning and executing animation based on my own designs</a></p><p>This is a very basic beginner-level animation code using framer-motion, and one can certainly dive in more to know how the states of the components and multiple pages of the react applications are being handled using Framer motion for the animations.</p><p><strong>Have a great day!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d63bbddd558e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>