JavaScript, React

ES2017 async/await with fetch in Redux (No Callback Hell anymore)

When we need to use third party API or any REST API in our web app, we need to wait for the response coming from the server.
Then in the success callback , we use that data and do other operations.And if we have more REST calls, we all know that it could end up being a Callback Hell

But if we use ES2017 async/await syntax , we can write our code as clean as possible with minimum lines of code.

Basic example of async/await is like below-

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  var result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"
}

asyncCall();

here var result = await resolveAfter2Seconds(); will wait to resolve the Promise and assign the returned data to `result` variable.
It seems like its executing the code line by line though it has asynchronous operation , which is awesome!

As of now , we know basic of async/wait , now we will use this inside redux ActionCreator. But first we will see how the code looks like without using async/await.
So our action creator code is –

export const getSpeakers = () => (dispatch, getState) => {
  return fetch(`${API_SERVER}/speakers`)
    .then(
      response => response.json(),
      error => {
        console.log("No! error occured.", error);
        throw error;
      }
    )
    .then(speakers => {
      console.log("speakers success", speakers);
      dispatch(saveSpeakers(speakers));
    })
    .catch(error => {
      console.log("Return Error by throwing", error);
      throw error;
    });
};

So here ^ is our action creator named `getSpeakers` which calls one REST API endpoint and then dispatch the speakers to the redux store.Here we can see we need to chain with `then`, `catch` etc which make the code a bit messy and hard to understand.

Now we will use async/await with fetch and will make our code good looking

export const getSpeakers = () => async (dispatch, getState) => {
  try {
    const response = await fetch(`${API_SERVER}/speakers`);
    const speakers = await response.json();
    console.log("speakers success", speakers);
    dispatch(saveSpeakers(speakers));
  } catch (error) {
    console.log("throwing Error", error);
    throw error;
  }
};

Here , we have added try/catch so that if any error happens, we can catch and take our decision what we want to do. Here in this case , I have just thrown the error, but we can dispatch another FAILURE action.
Ah , that made our code smaller,cleaner and easy to understand!

Cheers!

Standard
AngularJS, ASP.Net MVC, JavaScript, jQuery, jQuery AJAX, MVC WebAPI

Add Request Header for REST API Calling with AngularJS & jQuery

In the Web World , We always call REST APIs from our Web Applications .

When We call REST APIs through jQuery or AngularJS , they added few default Request Headers .

But many a time , we need to pass Custom Request Headers for different purposes.

A Common scenario is for Authentication we need to pass Customer Request header .

But how we can add this ?

Lets see the below samples :::

for jQuery , we can easily add Request Headers when we do AJAX Calling .

$.ajax({
            type: "POST",
            url: '/api/test',
            data: myObj,
            headers: { 'Custom-Header': 'Value'},
            success: function (resp) {
                alert(resp);
            },
            error: function (x, y, z) {
                alert(x);
            }
        });

In AngularJS , If we use $http for REST API calling , we can add Request Header like below , after we create AngularJS Module , we can do :::

myModule.run(['$route', '$http', function ($route, $http) {
            $http.defaults.headers.common.CustomeHeader = 'Value';
        }]);

Thanks

Standard
AngularJS, ASP.Net MVC, jQuery AJAX, MVC WebAPI

Delete Functionality : REST API with AngularJS $resource and jQuery-Ajax

For every Web Application , an important feature is Delete Functionality . We can not think a single app without it . But we already know how to develop DELETE Functionality inside a Web App . Then why is this article for?

Well , that’s true . But now , we will see how we can develop DELETE Functionality with $resource of AngularJS and/or also with jQuery . and for both cases , we have a REST URL of the server which is doing the real back-end thing .

Lets jump…

First lets see the Server code of REST API Delete Functionality . Here I have used .Net WebAPI . And the Method looks like below :::

public HttpResponseMessage Delete(int id)
        {
            //Delete Related Logics + Data Access calling etc
            return Request.CreateResponse(HttpStatusCode.OK);
        }

Now lets see the client side function of DELETE which is using AngularJS $resource .

$scope.delete = function() {
        $resource('api/Ticket/:id').delete({ id: $scope.ticket.Id }, function (data) {
            alert('Succeeded');
        });
    };

We can do the same thing by jQuery also , if we do not use AngularJS . But after learning AngularJS , you will never use jQuery 🙂 For jQuery lovers , we can do this like below with jQuery Ajax:::

$scope.delete = function () {
        $.ajax({
            url: 'api/Ticket/' + $scope.ticket.Id,
            type: 'DELETE',
            success: function (data) {
                alert('Succeeded');
            },
            error: function (x, y, z) {
                alert('Failed');
            }
        });
    };

Well , Thanks . Hope , you liked it .If you do , please share / subscribe …

Cheers 🙂

Standard