Categories
Blog Javascript Learning

Easy steps to create source endpoints with base url’s in react or any spa applications using ES6 tagged templates as a project utility and maintainbilty

Hello,

Here I would like to share with you a very handy and new innovative approach using ES6 Tag Literals template to ease of creating the base URL’s for use a single source of truth defined as library constants or utility code to refer as the single page application grows.

Let’s get hand dirty and mind free from hassle of maintaining and forming lines cluttered code and creating mess in many files as web application grows.

Hope you understand what I mean, developers get frustrated to follow the best practice as in tight project deadlines,

Heads up on I am currently using 2Factor.in endpoints in this post as I were using part of the project implementation, we will head in list out numbers as steps needs to follow for the quick implementation:

  1. We will save API key and API base URL in env file, (hope you are aware were it will lies in your project code, basically it lies at the core level of project director with named and with extension exactly, .env
SITE_2FACTORIN_API_BASE_URL=https://2factor.in/API/V1/
SITE_2FACTORIN_API_KEY=XXXXXX-dde0-23ec-XXXXXXXXXX

2. As I were using Nextjs, so I need to configure these env variables in next.config.js file to export it to the FE side contants(.js) file:

//next.config.js
module.exports = {
  publicRuntimeConfig: {
    SITE_2FACTORIN_API_BASE_URL: process.env.SITE_2FACTORIN_API_BASE_URL,
    SITE_2FACTORIN_API_KEY: process.env.SITE_2FACTORIN_API_KEY,
  },
};

3. Next we need to import publicRuntimeConfig object in our constants(.js) file

import { publicRuntimeConfig } from "./env.settings";

I am importing from .env.settings files which is actually using nextjs getConfig method to export publicRuntimeConfig variable, I am skipping that step to show here, once you search for docs on next/config you will get an idea what we are doing here.

4. Main part here it comes in contants.js file:

export const f2param1 = (param) => param || 1234657890;
export const f2param2 = (param) => param || "myTemplateName-OTP";

export function tagTemplate2FactorAPI(strings, param1, param2) {

  const { SITE_2FACTORIN_API_BASE_URL, SITE_2FACTORIN_API_KEY } = publicRuntimeConfig;
  const prefixBaseUrl = SITE_2FACTORIN_API_BASE_URL + SITE_2FACTORIN_API_KEY + '/';

  let str0 = strings[0] || ""; // "That "
  let str1 = strings[1] || ""; // " is a "
  let str2 = strings[2] || ""; // "."

  // We can even return a string built using a template literal
  return `${prefixBaseUrl}${str0}${param1 || ''}${str1}${param2 || ''}${str2}`;
}

export const factor2API_Endpoint = {
  CHECK_OTP_SMS_BALANCE: `BAL/SMS`,
  SEND_OTP_SMS: tagTemplate2FactorAPI`SMS/${f2param1()}/AUTOGEN`,
  SEND_OTP_SMS_TEMPLATE: tagTemplate2FactorAPI`SMS/${f2param1()}/AUTOGEN/${f2param2()}`,
  SEND_VERIFY_SMS: tagTemplate2FactorAPI`SMS/VERIFY/${f2param1()}/${f2param2()}`,
  CHECK_TRANS_SMS_BALANCE: `/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS`,
  SEND_TRANS_SMS: `/ADDON_SERVICES/SEND/TSMS`,
  SEND_TRANS_SMS_DYNAMIC_TEMPLATE: `/ADDON_SERVICES/SEND/TSMS`,
};

console.log(factor2API_Endpoint.SEND_OTP_SMS);
console.log(factor2API_Endpoint.SEND_OTP_SMS_TEMPLATE);
console.log(factor2API_Endpoint.SEND_VERIFY_SMS);

This is how the final code looks, but there is a catch in this code, just need to handle of passing the params dynamically to the constants property of the object, otherwise with the fixed 2 params in same file would do the trick.

Will share once I got the way of passing dynamic params values to object property in template literal invocation line.

—— Here I found it the other approach —- Edited: 00:44 (after few mins of publishing this post after above approach shared 🙂 )

export function tagTemplate2FactorAPI(strings, ...keys) {

  const { SITE_2FACTORIN_API_BASE_URL, SITE_2FACTORIN_API_KEY } = publicRuntimeConfig;
  const prefixBaseUrl = SITE_2FACTORIN_API_BASE_URL + SITE_2FACTORIN_API_KEY + '/';

  return (function (...values) {
    let dict = values[values.length - 1] || {};
    let result = [strings[0]];
    keys.forEach(function (key, i) {
      let value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });

    result.unshift(prefixBaseUrl); //added this line to prefix with base url path
    return result.join('');
  });
}

export const factor2API_Endpoint = {
  CHECK_OTP_SMS_BALANCE: `BAL/SMS`,
  SEND_OTP_SMS: tagTemplate2FactorAPI`SMS/${0}/AUTOGEN`,
  SEND_OTP_SMS_TEMPLATE: tagTemplate2FactorAPI`SMS/${0}/AUTOGEN/${1}`,
  SEND_VERIFY_SMS: tagTemplate2FactorAPI`SMS/VERIFY/${0}/${1}`,
  CHECK_TRANS_SMS_BALANCE: `/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS`,
  SEND_TRANS_SMS: `/ADDON_SERVICES/SEND/TSMS`,
  SEND_TRANS_SMS_DYNAMIC_TEMPLATE: `/ADDON_SERVICES/SEND/TSMS`,
};

 console.log(factor2API_Endpoint.SEND_OTP_SMS(12311312, 'newTemplate-newOTP'));
 console.log(factor2API_Endpoint.SEND_OTP_SMS_TEMPLATE(5656565, 'newTemplate-newOTP'));
 console.log(factor2API_Endpoint.SEND_VERIFY_SMS(456646545, 'newTemplate-newOTP'));

Output log of the above code:

Solution, I found right after reading the basic guide on Tagged template on Mozilla documentation on Tagged Templates

Thanks for reading.

Happy Learning.

Categories
Javascript Learning Tech

React functional child component not re rendering on parent state change?

Hello,

I was also looking answer for similar question.

Here is the quick solution I found and worked for me, hope it helps you too in some scenario we might mistaking

Pitcure (a)

As in the (a) was getting null as a data response in the react child component (where the text shown “Reset linked expired…”) , where actually data was updating from parent component and passed to react child component named <ResetPasswordForm … /> as ‘data’ as a prop, here its full code look like:

function ResetPassword({ }) {
  const router = useRouter();
  const [resetPasswordData, setResetPasswordData] = useState(null);



  useEffect(() => {
   
    const { query } = router;

    if (query && query?.token && query?.email) {
      console.log(query);
      setResetPasswordData({
        ...query
      });
    }
    return () => {
    }
  }, [router]);

  return (<React.Fragment>
    <GlobalCookieContextProvider>
      <div className="app-page" id="appPageEle">
        <Layout>
          <div className={styles.loginFormWrapper}>
            <div className={styles.loginBox}>
              <div className={styles.loginBoxLeft}>
                <LeftBoxImage />
              </div>

              <div className={styles.loginBoxRight}>
                {JSON.stringify(resetPasswordData, 0, 2)}
                <ResetPasswordForm title={'Reset Password'} data={resetPasswordData} />
              </div>
            </div>
          </div>
        </Layout>
      </div>
    </GlobalCookieContextProvider>
  </React.Fragment>);
}

Solution 1 : To fix the issue of null, I have to remove the wrapping GlobalCookieContextProvider component as I was not passing any prop to it and also I have no use in this Reset Password Main component, so after removing the wrapping Provider component it worked like as expected, Boom!.

Results of JSON output attached to the form

Picture (b)

Hence start receiving data from parent react component when state change updated dynamically from URL query params as expected.

But wait, Solution 1, was not working still as expected in certain refreshes, then work around did and moved the all query params check code from nextjs page component to its child level component named ResetPasswordForm component and everything finally working as expected again.

Hope you enjoyed the post, let me know in comments if confused you, will try to re-try to post again.

Happy we learning!

Conclusion

First found the wrapping un-used React Provider component, causing a stop of re-ending of react child component when parent component state update done, but after some further testing its was still breaking, final solution found in moving the router query params check and updating state into the first level child component itself which does the expected checks in useEffect() and render the component fairly with the expected results on query fetch done.

Categories
Javascript Learning Learning Tech

How I have resolve, Module not found, Can’t resolve ‘optimism’

Hello welcome to this post.

Straight to the answer, here it goes:

Tried running first nextjs app

λ npm run dev

> developfe-dev@1.0.0 dev
> next

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from F:\windows\developapp\code\.env
info  - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
error - ./node_modules/@apollo/client/cache/core/cache.js:1:0
Module not found: Can't resolve 'optimism'

Import trace for requested module:
./node_modules\@apollo\client\cache\index.js
./node_modules\@apollo\client\core\index.js
./node_modules\@apollo\client\index.js
./pages\_app.js

https://nextjs.org/docs/messages/module-not-found
Terminate batch job (Y/N)?
^C

Next reinstalled package



F:\windows\developapp\code (main -> origin) (developfe-dev@1.0.0)
λ npm i @apollo/client@latest --save

added 9 packages, changed 1 package, and audited 1119 packages in 13s

90 packages are looking for funding
  run `npm fund` for details

6 vulnerabilities (4 low, 2 high)

To address issues that do not require attention, run:
  npm audit fix

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.

Then run again! boom!

F:\windows\developapp\code (main -> origin) (developfe-dev@1.0.0)
λ npm run dev

> developfe-dev@1.0.0 dev
> next

ready – started server on 0.0.0.0:3000, url: http://localhost:3000
info – Loaded env from F:\windows\developapp\code\.env
info – Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
event – compiled successfully

So, here is the simple answer to the question.

Thanks for reading and Happy Learning!

Categories
Blog Learning Tech

How to use if else conditions in laravel blade view or for html code?

Hello, thanks for checking out here!

Here is the quick and short answer with the examples:

Example 1
<img src="@if($category->image) {{ ($category->image) }} @else {{'https://via.placeholder.com/50'}} @endif" alt="{{ $category->name}}" width="50" height="50" />

This is what I was looking for my part of development laravel! same you can achieve for the html blocks: here is the example:

Example 2
@if ($message = Session::get('success'))
    <script>
      if(window.toastr)
          toastr["success"]("{{ session()->get('success') }}"); 
    </script> 
@endif
Example 3
@if ($message = Session::get('success'))
  <div class="alert alert-success">
     session()->get('success')
  </div>
@endif

To use elseif just use following syntax @elseif(condition) along your code or between.

Thanks & Happy learning Laravel!

Categories
Learning Tech

If Laravel created_at or updated_at SQL error, what to do?

Hello, welcome to my random post.

Quick to elaborate, what I was doing what I found it right to fix.

I am building an application with Laravel and I was facing with this below error:

// Illuminate\Database\QueryException
// SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘created_at’ in ‘order clause’ (SQL: select * from food order by created_at desc limit 10 offset 0)

The cause of such error is when we don’t have column name in our database table, as to be created_at and updated_at.

In my case I was following camel case styles column names in database table: createdAt and upatedAt, so it was cause of this error and further to it, as I were looking for the solution and found that I am using latest() method to fetch the code (which is not allowed when don’t have laravel style column names of our database table), example like below

$food = Food::latest()->paginate(10);

so we have to have a columns names with created_at and updated_at in our database table, if want to use latest() method

Otherwise we need to change the method to orderBy() or first() method to fetch the result from database, also remember to add arguments to orderBy method/function like below, otherwise you would face again error of arguments need to be passed.

$food = Food::orderBy('createdAt', 'desc')->paginate(10);

Thanks for reading and happy coding. Have a nice day 🙂

Categories
Blog Javascript Learning Tech

Taking Random Angular Quiz, Got Results – Jat

Hello, welcome and thanks to visit here to read my this short random post.

I was looking to take a random angular quiz to test my ability on Angular after a year around how much I remember about it, as because currently I mostly working with React and GraphQl, ApolloServer and Client and loving NextJS.

So after searching on Google, I landed up over this blog (here) (not an intention to use the link wrongly here), I took the Quiz and here is my result below with the image.

I too read some articles in the morning and look for tips and tricks on Angular so I can heads up well for the next interview on Angular 🙂

So I tried Quiz from the above blog link and here it is:

Question ah? How it could prove its my result, you can check on the full screenshot from my computer currently and tiny image up on the top corner and below on the Task bar with Chrome Active.

JAT-angular-quiz-result-with-rest-of-the-WORLD!

That’s all I would like to share with you all.

Thanks for reading and visiting. Have a great time and year’s ahead!

P.S. yes I forgot to mention, I am next going to take up more quiz and sharp my Angular blade more finer as possible as to be! Happy Learnings!

Categories
Learning Tech Uncategorized

Tips & Tricks how they do it in laravel, now we can too do it

In day of my learning on PHP Laravel building application from scratch with googling help and docs.

How to foreach or for loop on html select input or dropdown field in laravel blade file

<select class="custom-select jsUpdateOrderStatus"   id="ddlTodayOrdersStatus{{$loop->index}}"          name="ddlTodayOrdersStatus{{$loop->index}}"
data-orderid="{{$order->orderId}}" >
     @foreach ($orderStatus as $status)
         <option value="{{$loop->index}}" 
         {{$order->status === $loop->index ? "selected" : "" }}"  
         data-loopIndex=" {{$loop->index}}">{{$status}}</option>
     @endforeach
</select>

To Note : $order is passed as dynamic object to the blade file in which this code will be implemented, its for just example to explain. (hint: make sure your laravel directive/code are intended properly in blade files, otherwise it might throw error to the view)

How to add format date to html in laravel blade file

<p>Example code 1: </p>
<p>{{ Carbon\Carbon::parse($order->createdAt)->format('d-M-Y H:i:s') }}</p>

<p>Example code 2:</p>
<p>{{ Carbon\Carbon::parse($order->createdAt)->diffForhumans() }}</p>

Using ajax script code in laravel blade file (just for ajax javascript syntax example):

<script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    </script>
    <script>
        // alert('javascripts section loaded test!');
        $(function() {
            // alert("jQuery works test!") ;
            
           $('.jsUpdateOrderStatus').change(function(e) {
              
            //   console.log('change fired! ');
              
              const curTargetEle = $(e.target);
              const value = curTargetEle.val();
              const orderId = curTargetEle.data('orderid');
              const curDDLUpdatedText = curTargetEle.find('option:selected').text();
              const curDDLUpdatedTextInital = curDDLUpdatedText.substring(0,1);
              const curSiblingLabelEle = curTargetEle.siblings('.input-group-prepend').find('label');
              
              if(!value || value === "") {
                  console.error('value not passed'); 
                  return;
              }
              
              
            //perform AJAX call
            // console.log('jsUpdateOrderStatus fired ', value, orderId);
            
            const payload = { 
                _token:  $('meta[name="csrf-token"]').attr('content'),
                orderId,
                value
            };
            
            if(confirm("Are you sure, you want to change order status?")) {
                $.ajax({
                    url: "{{route('update-order-status')}}",
        			type: "post",
        			cache: false,
                    data: payload,
                    // dataType: 'json',
                    // data:"{id:$(this).data('fid')}"
                }).done(function(resp) {
                  
                  //success
                  console.log("Order status success response: ", {resp});
                  
                  if(resp && resp.success) {
                      
                      curSiblingLabelEle.text(curDDLUpdatedTextInital);
                      
                      const msg = `Order ${orderId} set to ${curDDLUpdatedText} succesfully`;
                      toastr["success"](msg || resp.message);
                      
                      location.reload();
                  }
                  
                   }).fail(function(err){
                  //failure
                   toastr["error"](err.responseText || err.status);
                  console.error("Order status error response: ", {err});
                });
            }
           });
               
        });
    </script>


To note: here some ccode you won't find relevant to your need, you may remove them, this is to show a general idea of ajax JavaScript side of implementation on some html input/select field change event to dynamically handle request. 

Conditionality showing html code in Laravel blade file using Laravel @if directive

<ul class="nav nav-tabs" id="myTab" role="tablist
    @if (count($todayOrders))
      <li class="nav-item" role="presentation">
        <a class="nav-link active" id="todayorder-tab" data-toggle="tab" href="#todayorder" role="tab" aria-controls="todayorder" aria-selected="true">Today's Order <sup class="badge badge-pill badge-dark">{{count($todayOrders)}}</sup></a>
      </li>
    @endif
  <li class="nav-item" role="presentation">
    <a class="nav-link  @if (!count($todayOrders)) active @endif " id="allorder-tab" 
        data-toggle="tab" href="#allorder" role="tab" aria-controls="allorder" aria-selected="false">All Orders <sup class="badge badge-pill badge-dark">{{count($orders)}}</sup></a>
  </li>
</ul>

To note: this is just example you can do the same with any other kind of html codes.

Conditionality setting class to html tag using Laravel @if directive

class="nav-link  @if (!count($todayOrders)) active @endif " 

HTML code example:
<a class="nav-link active" id="todayorder-tab" data-toggle="tab" href="#todayorder" role="tab" aria-controls="todayorder" aria-selected="true">Today's Order <sup class="badge badge-pill badge-dark">{{count($todayOrders)}}</sup></a>

Thanks for visiting & reading this post. Hope it help you in your way of building applications.

Categories
Javascript Learning Tech

How to add Buy me coffee script dynamically into React application or Javascript

Stumble upon in the search of adding Buy me coffee script into react application land to the following wonderful hook solution to add script to react on stack overflow here

I will also add up here the update code of stack overflow which helped in the solution (for incase above shared link will be changed in future, and all the code credit is to the author of stack overflow user)

Update:
Now that we have hooks, a better approach might be to use useEffect like so:

useEffect(() => {
  const script = document.createElement('script');

  script.src = "https://use.typekit.net/foobar.js";
  script.async = true;

  document.body.appendChild(script);

  return () => {
    document.body.removeChild(script);
  }
}, []);
Which makes it a great candidate for a custom hook (eg: hooks/useScript.js):

import { useEffect } from 'react';

const useScript = url => {
  useEffect(() => {
    const script = document.createElement('script');

    script.src = url;
    script.async = true;

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    }
  }, [url]);
};

export default useScript;
Which can be used like so:

import useScript from 'hooks/useScript';

const MyComponent = props => {
  useScript('https://use.typekit.net/foobar.js');

  // rest of your component
}

Solution, I have added on top a ‘config’ param to the useScript function for easy BMC Buy me coffee widget attributes to get added to script object dynamically:

const useScript = (url, config = null) => {

  useEffect(() => {
    const script = document.createElement("script");

    script.src = url;
    script.async = true;

    if (config && Object.keys(config).length) {
      for (let key in config) {
        script.setAttribute(key, config[key]);
      }
    }

    // console.log(script);
    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    };
  }, [url]);
};

export default useScript;

Boom!

Categories
Javascript Learning Tech

How to play with Graphql playground for Mutation’s?

Okay, well I was also looking for solution to this and here it is:

Mutation example of adding employee using Graphql Playground, most important step after you have added the code below to playground tab window:

# Write your query or mutation here
mutation AddEmployee(
  $name: String!,
  $phoneNumber: String!,
  $email: String! ,
  $designation: String,
  $image: String) {
    addEmployee(employee: 
      { name: $name, phoneNumber:$phoneNumber, email: $email, designation: $designation, image:$image },
    ) 
      {
        emp_id
        name
      }
    
}

You need to add your JSON payload to QUERY VARIABLES tab window (which is closed by default on below main playground window, without this input payload you will not see results, but error. (keep an eye on here while you make mutation test in graphql playground)

grapql-mutation-example-with-query-variable-input-parameters

Thanks for visiting!

Categories
Blog Tech

angular ng serve command throws error: An unhandled exception occurred: Project does not exist

If you facing with such problem, you may refer to following link for the solution. I have posted this question here on StackOverlow Hope it helps someone. Thanks.