Our Global Presence
Canada
57 Sherway St,
Stoney Creek, ON
L8J 0J3
India
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
USA
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
Organic traffic is a great way to get eyeballs on your website and Google is the most popular search engine of choice that you can use to get that organic traffic coming.
Although Google ranks your site based on a lot of metrics, how fast your website loads is one of the critical factors.
Websites that load quickly are not just great for rankings but also for the overall user experience.
Since most of us developers( especially indie developers) are using JavaScript frameworks, such as React and Angular, which probably do a client-side rendering of data, the speed at which data is fetched forms an important aspect of the development process.
There is a simple way of making your site load faster, and that is caching and CDN(Content Delivery Network).
Using a combination of both can lead to miraculous drops in time taken to load the first byte.
In this blog, I will demonstrate caching with an example using Redis and also explain what is CDN.
Caching, in layman’s language, is storing data that you think might be used frequently into memory(called cache).
So the next time you need that data, you check whether it’s stored in the memory and if not, then you make a call to the database to fetch it and maybe store it into the cache for future use.
As you can see from the image above, caching is simply a layer of a data structure containing frequently accessed data between your data source and the app.
Not all data needs to be cached. For example, a user’s personal setting or shouldn’t be cached on the server. However, you can always store them in the client’s local storage for faster access.
Caching of data is one of the simplest ways to reduce the load time, at the same time, you have to be smart about how you cache your data.
As stated before, frequently accessed data should be cached to provide a responsive and quick experience.
Different developers have different caching strategies depending on their preferences and needs. If you want me to cover various common caching strategies, then drop a response to this blog.
Below are some examples of items that you should cache:
Authorization & Session Tokens
Landing page data that doesn’t change often(such as recent projects in a portfolio site).
Blog and post drafts can be stored in cache for a while and then inserted into the database after a fixed amount of time.
Real-time comment streams & analytics.
Although you are free to use whatever option you are comfortable with, I highly recommend at least checking Redis out.
Redis is an open-sourced in-memory data structure store that has familiar data types such as lists, dictionaries, strings, hashes, etc.
It is a key-value data store with extended abilities such as the ability to set expiry dates.
Redis is the most loved database as per the Stack Overflow 2021 survey.
AWS’s MemoryDB for Redis is a great choice if you need a durable transactional log that stores data across multiple Availability Zones.
Installing Redis is incredibly straightforward if you are on Linux.
Head over to the Redis download page and download the latest stable version available or you can simply run the following command in your terminal:
sudo apt-get install redis
Once you are done installing Redis, simply type redis-server to spin up a Redis server. The default port of this server is port 6379.
However, if you are on Windows, there are two options.
You can either follow the simple guide on how to install an outdated Redis on your Windows machine or you can use Windows Subsystem for Linux(WSL) and get the latest Redis.
I personally went with the WSL way and it created an Ubuntu 20.04 system for me to install Redis and any other packages I might need in the future.
There are plenty of guides available online on how to get started with Redis, hence I will just be providing a demo of what Redis can do to speed up your website.
I will be creating a simple Node.js server that fetches some data from the web and then sends them to its clients and later we will be adding caching to it and see the massive difference.
Below is a server that simply fetches the data from a data source and then passes it along to the client.
const express = require('express'); const app = express(); const redis = require('redis'); const fetch = require('cross-fetch'); const cacheClient = redis.createClient(); app.get('/', async (req, res, next) => { await fetch('https://jsonplaceholder.typicode.com/photos') .then(response => response.json()) .then(json => { console.log('Newly fetched data') return res.json({ data: json }); }) }); app.listen(3000, () => console.log('listening on port 3000'));
You can see the response time in the image attached below:
Now we will implement caching using Redis.
First of all, we need an npm package.
npm i --save redis
Once this is installed, we will import it into our server.js file & create a client.
const redis = require('redis'); const cacheClient = redis.createClient(); // => Redis client
We need to edit our app.get() function and add caching logic to it.
It’s simple if-else logic. We first check if the data is present in our Redis server or not by calling the Redis client and using the .get() to get data.
If the data is not present, then we make a call to our data source to get fresh data. We insert this data into our Redis store by calling the .setex() function on our Redis client.
cacheClient.setex('sample',60,JSON.stringify(json));
The first parameter is the name(key) of the data we want to store, followed by the time to expire, and then finally the actual data(value) goes in as the third parameter.
We are using JSON.stringify() method to convert our JSON data to a string data type.
With the data stored in the Redis store, the next time the app.get(‘/’) function is called, the client will be able to fetch the data from the Redis server instead of fetching from our original data source.
With this implemented, we can instantly see amazing results as the time taken is just 52ms compared to 1301ms from before.
This was a very simplistic view of caching and Redis is capable of much more than caching and can even be used as a permanent storage option.
Our final server.js file will look like this:
const express = require('express') const app = express(); const redis = require('redis'); const fetch = require('cross-fetch'); const cacheClient = redis.createClient(); app.get('/', async (req, res, next) => { await cacheClient.get('sample', async (err, data) => { if (err) console.error(err); if (data) { console.log('Data was cached before') return res.json({ data: JSON.parse(data) }); } else await fetch('https://jsonplaceholder.typicode.com/photos') .then(response => response.json()) .then(json => { console.log('Newly fetched data') cacheClient.setex('sample', 60, JSON.stringify(json)); return res.json({ data: json }); }) }) }); app.listen(3000, () => console.log('listening on port 3000'));
Caching data on the server is surely a great improvement but what about caching large HTML, video & image files?
CDN provides a simple solution to this issue. It is important to know that CDN and caching are not the same.
While CDN does cache content, not everything that cache data can be called a CDN.
CDN refers to a geographically distributed group of servers that work together to provide fast delivery of sites & other assets(like image & video files).
Popular sites such as Netflix and Facebook leverage the benefits of the CDN and deliver content quickly to you using the nearest group of servers near you.
CDN stores a cached copy of your content in multiple locations throughout the world.
So if someone from Australia visits your UK-hosted site, they will instead visit the nearest CDN server available to Australia and get a cached copy of your UK-hosted site.
This also saves bandwidth costs and increases reliability & uptime.
In some platforms and hosts, a CDN is at your disposal by default, and generally, using it is as simple as adding a header to your HTML file.
Personally, in my experience, I have found Vercel’s CDN to be the simplest to use with a good, detailed guide with a useful feature that prevents your data from being stale(outdated).
In Vercel, you just need to add a header to inform the CDN that the site needs to be cached. An example header is given below:
Cache-Control: s-maxage=1
It is worth noting that any data that you load client side will not be included in your site’s cached CDN copy. This is because the data is loaded dynamically on the client-side and not server-rendered.
However, you can always cache the data that is being loaded on the client-side via Redis, CDN, or any other option available to make the dynamic loading faster.
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
As the world leans more towards digital technologies, as more businesses focus on online and physical presence, and as content continues to dominate, web development becomes even more essential.
Accordingly, one of the best programming languages for better frontend development is JavaScript. That’s why, today, we want to show you some of the top JavaScript trends that can help boost your web application’s success.
Dark mode has been one of the recent web development trends that have been blowing up everywhere. As a result, almost all popular apps can switch to a dark mode or stick with the standard light mode.
Moreover, since it uses less color and brightness, the dark mode also helps preserve the battery and makes it last longer. Some people also claim that dark selection can be beneficial for specific visual impairments. For web designers, the dark mode also allows them to use colors more creatively, as the black background of the dark option can help colors stand out even more.
Using this script snippet results in the widget appearing on your site automatically so that users can conveniently switch between their preferred themes. The plugin is relatively lightweight, and since it uses local storage, it will remember and save the last chosen theme.
Another JavaScript trend that remains on top for a few years and is gradually garnering more popularity is React.js. React is an open source, frontend, and entirely free JavaScript library for developing smooth and effective user interfaces, especially for single-page apps.
Facebook developed the React library several years ago and has built it into one of the most popular JavaScript libraries for frontend developers. In 2020, 80% of front-end developers were using React only. In addition, many companies like WhatsApp and Airbnb have taken on this library as well.
The reason behind this is that React offers a lot of convenience and benefits for today’s developers. The programming library is easy to learn and even easier to use. It comes with many tutorials and documents explaining how to utilize the library best.
If you are already skilled in JavaScript, picking up React will be no trouble at all, and you will find yourself easily using it within a few days. React also comes with a lot of reusable components, which are a lifesaver for any developer.
The JavaScript framework uses small user interface components, which you can use to create more prominent parts or reuse again to save your time and efforts. All the pieces have their logic, and they can control their rendering, which allows you to use them again wherever and whenever you need them quickly.
Convenience is important to me. It helps me navigate the flow more efficiently. How about you?
All this makes it easy to develop and maintain apps. In addition, since you are reusing the same essential components, you can keep your projects’ same feel and look. Other popular libraries besides React include Angular, Vue, and Svelte.
A better user experience does not just include a smooth and fast website. It also contains a unique and creatively designed website and what better way to show off your creativity than through animations.
Animations can make your website visually striking and keep visitors hooked on your page. They can help differentiate your website from all the usual static websites. If you think you need to go out and do some special courses on animation, we’ve got some good news.
JavaScript has several libraries that allow you to integrate animations on your website easily. These libraries include anime.js and JSTweener. You can input these into your website code, customize the code, and voila! Your animations are ready.
Especially if you are running a business or have a product checkout page on your website, employing data visualization tools can significantly help you in many ways. First, it can improve the user interface and experience by filling out fields quickly and accurately.
As a result, the whole checkout experience for visitors and potential customers becomes much more accessible and makes them more willing to follow through on their purchases. Due to all these benefits, data visualization is a big trend within JavaScript for business and marketing purposes.
All you need is a little <input />
One specific library that is quite useful is Algolia Places. It allows you to create much more efficient forms, which help inaccurate data input and quick form filling. In addition, you can incorporate a map that will conveniently display a specific location for better data visualization.
Algolia Places uses OpenStreetMap’s extensive database and is incredibly fast to use. In addition, it can handle some typing mistakes and simplifies the entire checkout process for users.
Incorporating full-screen videos on your webpage is one of the most popular JavaScript trends developers utilize these days. Again, rather than creating an essential static website, incorporating dynamic videos and GIFs can help make your website more interactive and offer a better user experience.
A better user experience, then, can help drive more traffic to your website, making it easy to push your content, raise awareness about your brand and increase your ROI for your marketing and business objectives. But, how can you add full-screen videos to your website?
JavaScript offers a great resource: Bideo.js. This library makes it super easy to add full-screen videos to your website’s background. While it takes a while to load, you do not have to write endless code to incorporate the video smoothly.
The library has everything you need to add the videos along with several customization options quickly. The code works great for screens of all sizes and various platforms as well. This JavaScript tool can help play high-quality and engaging videos smoothly in the background, whether a computer or mobile. You can resize the video according to the browser, and it is also easy to implement using CSS or HTML.
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
JavaScript is a very powerful programming language these days. There is a lot that you can do with it. In addition to that, JavaScript has a huge ecosystem that allows you to discover a lot of useful tools, frameworks, and libraries.
JavaScript has a lot of powerful features and tools that make the life of the developer much easier. The syntax contains a lot of shorthands that you can use to write JavaScript code much faster and reduce lines. Especially in the latest ECMAScript specifications.
In this article, we will give you a list of shorthands that you can use in JavaScript. So let’s get right into it.
Normally, to convert a string to a number, we use the method parseInt() . However, there is a shorthand that allows us to do that.
By using the unary operator + , we can easily convert a string into a number.
Here is an example:
let speed = "60"; console.log(typeof speed); //string console.log(typeof +speed); //number console.log(+speed); //60, not "60".
As you can see, only by adding + at the beginning of the variable speed , we were able to convert the speed to a number.
There is also another shorthand to convert from a number into a string. It’s by simply adding an empty string to the number.
Here is an example:
let speed = 100; speed += ""; //returns "100" , not 100. console.log(typeof speed); //string
Another shorthand is the ternary operator, it allows us to easily write conditional statements in a short way using the keywords ? and : .
Here is an example using IF else statements:
Longhand:
let speed = 80; if(speed < 30){ console.log('slow'); }else if(speed > 60){ console.log('fast'); }else{ console.log('between 30 and 60'); } //output: fast
Here is the same example, but now using the ternary operator instead:
Shorthand:
let speed = 80; console.log(speed < 30 ? 'slow': speed > 60 ? 'fast' : 'between 30 & 60'); //output: fast
As you can see, by using the ternary operator shorthand, we were able to easily reduce the amount of code we had to write. It only took us 2 lines of code to write the conditional statements.
Have a look at the below example using an IF statement.
Longhand:
let isOnline = true; if(isOnline){ console.log("Online"); } //returns "online"
We can write the same statement using the short circuit && . Here is the example:
Shorthand:
let isOnline = true; isOnline && console.log("Online"); //returns "online"
The short circuit evaluation && is one of the shorthands that allow you to write short conditionals. It’s used between two values, if the first value is truthy, it returns the second value. Otherwise, it returns the first value.
The best shorthand to flatten a multidimensional array is by using the method flat(). We have seen, a lot of developers use the method filter, concat, and all other long ways to flatten an array. Maybe because they don’t know about the flat method yet.
So this amazing method allows you to flatten an array in one single line of code. It accepts one optional argument(number), which is the level of flattening(how deep you want to flatten an array).
Here is an example:
let numbers = [9, [102, 5], [6, 3], 2]; numbers.flat(); //returns [9, 102, 5, 6, 3, 2]
When it comes to merging and cloning arrays in JavaScript, the spread operator {…} is the best shorthand you can use.
Merging arrays:
const employees = ["Chris", "John"]; const entrepreneurs = ["James", "Anna"]; //merging both arrays to a new array. const all = [...employees, ...entrepreneurs]; console.log(all); //output: ["Chris", "John", "James", "Anna"]
Cloning an array:
const numbers = [4, 8, 9, 0]; //cloning the numbers array. const clone = [...numbers]; console.log(clone); //output: [4, 8, 9, 0]
Mostly when we want to loop through an array using a for loop, we do it like this:
Longhand:
const users = ["John", "Chris", "Mehdi", "James"]; for(let i = 0; i < users.length; i++){ console.log(users[i]); } /*output: John Chris Mehdi James */
But we can achieve the same thing using the loop for of shorthand:
Shorthand:
const users = ["John", "Chris", "Mehdi", "James"]; for (let user of users){ console.log(user); } /*output: John Chris Mehdi James*/
Arrow functions are a shorthand that allows you to easily write functions in a short way and reduce your code.
Here are the examples:
Normal function:
function addNums(x, y){ return x + y; } addNums(6, 5); //11
Arrow function:
const addNums = (x, y)=> x + y; addNums(6, 5); //11
As you can see, these are some of the popular shorthands that you can use in JavaScript. They allow you to reduce code syntax and keep your code short as much as you can.
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
We always say that JavaScript is full of surprises. It never fails to amaze us. Every day, we learn something new about this programming language. Something which is very small but can make a huge impact on your code. Something which is worth sharing.
In this article, we’re going to share eight JavaScript hacks that you can use in your day-to-day stuff. So let’s learn something new!
It’s very common to use event listeners in your web app, not just in Vanilla JS applications, but also in modern JS frameworks and libraries like Angular and React.
To cite an example, let’s say we want to do something on a button click. We can use event listeners here. Often, we want to act whenever a specific event fires. But what if we want to do it only once?
Not to worry. We can actually execute our event listeners only once by simply doing this:
const button = document.querySelector('button'); button.addEventListener('click', () => { console.log('We will only run once'); },{ once: true })
To be honest, all of us have faced a situation where we felt like our web application is getting slower and we are not able to find out why. We’ve felt like we are doing everything as it should be, but still the browser is taking time to show the first content of our application.
Well, this might be because of long scripts getting executed before HTML. Often, we add our scripts inand we forgot that the next statements will not be executed until the script in <HEAD> finishes its execution.
We can simply use the defer attribute with our scripts to execute them after the HTML content.
/* No matter where you place this script tag inside the HTML, this will only run when the HTML content is completely loaded. */ <script src="main.js" defer></script>
It’s always recommended to use shorthand to make our code look cleaner. As no application can survive without conditionals like the if statement, we should know the shortcuts for that, too. And thankfully, JavaScript provides the && operator.
We can shorten our conditional checking by using the && operator.
let condition = true; // Long way if (condition) { someFunction(); } // Short way condition && someFunction();
We can simply generate a random number from a given range with just one line of code. These kinds of tricks are very useful in real-world applications.
function randomNumber(num1, num2) { return Math.random() * (num2 - num1) + num1; } console.log(randomNumber(50, 100)); // Expected output - random number between 50 and 100 (50 and 100 will be inclusive)
This is one of the hacks which We love the most. We can empty an array just by giving the value 0 to its length property.
let sampleArray = ["John", "Bob", "Mark", "Alex"]; sampleArray.length = 0; console.log(sampleArray); // Output - [] (it's empty now)
We can use the Object.entries() method to check whether an object is empty or not. Since Object.entries() returns the array of the object’s enumerable properties, therefore if the length of that array is 0, that means the object is empty such that the object has 0 property.
let sampleObj = { name: "Mark", occupation: "Developer" }; let emptyObj = {}; console.log(Object.entries(sampleObj).length === 0); // false console.log(Object.entries(emptyObj).length === 0); // false
From ES6, we have a new concept in JavaScript which is called Set.
"Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection." — MDN Docs
Since Set in JavaScript is a collection of items that are unique, i.e., no element can be repeated, therefore we can use it to filter duplicate values from an array.
This trick is again very simple but very useful. First, we will convert our array into Set, and as Set doesn’t have duplicate values, our new Set will have unique values from our array. Then we simply convert this new Set back into an array.
let namesArray = ["John", "Bob", "Mark", "Alex", "Mark", "Alain", "Bob"]; console.log([...new Set(namesArray)]); // Output - ["John", "Bob", "Mark", "Alex", "Alain"]
Since objects in JavaScript are reference types, we can’t simply use = to clone them, so with the below three methods, you can properly clone an object using just one line.
const person = { name: "Mark", username: "@markcodes" }; // Using Object.assign() Method const clonePerson1 = Object.assign({}, person); // Using JSON const clonePerson2 = JSON.parse(JSON.stringify(person)); // Using Spread Operator const clonePerson3 = { ...person };
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
Web developers love nothing more than finding amazing extensions that accelerate the development process.
One such tool is Chrome DevTools, which offers a lot of features and it is the go-to tool for frontend developers, of all levels.
DevTools has a wide array of features and options, and Google has done a fantastic job documenting this tool.
However, despite the comprehensive documentation, there is still a list of helpful tools and features that most developers don’t know about.
From emulating mobile devices to finding useless JavaScript code, we’ll be covering 9 secret features the DevTools has to offer in this blog.
Your website will be accessed by people from around the globe using devices of different sizes and platforms.
You can build websites that are responsive using media queries, but what about network speed?
Not every one of your visitors will have the same network speed, hence you need to check how your site behaves with different network speeds.
Luckily, DevTools has the option to switch between 3 network presets:
You also get the ability to add a custom profile.
You can find this feature under the Network tab, by clicking on the “No throttling” dropdown menu.
DevTools has an excellent code editor inbuilt.
If you’re someone who edits CSS or any code using this tool, you will absolutely love the multi-cursor support.
It’s very easy to set up as well. All you need to do is press and hold Ctrl( Command on Mac) and click on lines where you want multiple cursors.
You can also undo your selections by pressing and holding Ctrl(Command on Mac) + U.
Moreover, you can also press Alt and drag to get multiple cursors. You can see the implementation here.
For me, dark mode increases visibility & reduces eye strain. There are many upsides to using dark mode, as well as downsides.
Various articles cover this topic.
We use the dark mode wherever possible, from the Twitter app to our calculator app.
DevTools is no exception.
To enable the dark mode, open the Settings by clicking the three vertical dots present in the right corner of the screen.
Then go to Preferences > Appearance > Theme and finally select Dark.
You can quickly open a Command Menu by pressing Ctrl(CMD on Mac)+Shift+P when DevTools is opened.
It provides a fast way to navigate the DevTools and over time, you become familiar with it.
This feature is handy if you are familiar with VS Code’s Command Palette.
You can delete the > and replace it with ? to see all the features offered by this menu.
Modern JavaScript apps are becoming increasingly complicated and rely on a ton of third-party libraries.
There’s always some code that’s not used and is rendered redundant.
DevTools helps you locate such redundant code that may unnecessarily be hampering your site speed.
To do so, click the three vertical dots on the top-right corner of DevTools. Then click More Tools and select Coverage.
All you need to now is reload the page and the newly popped up panel will display the unused JavaScript code.
You can see the total bytes as well as the unused bytes along with the visual usage bar.
If your primary browser is some other browser that doesn’t offer such tools, and you only use Chrome for the Devtools, then this feature can be incredibly useful to you.
There is a global option under DevTools settings to auto-open DevTools for popups.
However, the better way of doing this is by starting DevTools not just on popups but with the Chrome browser itself.
You can do so by adding the following line as a property on Google Chrome.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --auto-open-devtools-for-tabs
And for Mac users,
--auto-open-devtools-for-tabs
You can refer to the answers here to learn more options to enable DevTools.
Color Picker is a great way to select the exact color you need and be able to easily add it to the CSS of your site.
DevTools offers a color picker and accessing it is a very straightforward process.
Go to the Elements tab and from there select the Styles panel to see the CSS.
Simply click on the color square (not the value) and the color picker will show up.
The color picker has the ability to easily convert between color modes, like from HEX to RGBA.
Over 60% of all online searches are performed by mobile devices, making responsive web design a critical part of web development.
Fortunately, DevTools offers a mobile emulator, which has predefined height and width which match that of some popular mobile devices like iPhone, Pixel, Surface, and iPad.
Open DevTools and click the Toggle Device Toolbar as shown in the media above.
You can also choose between mid-tier or low-tier mobile from the “No Throttling” drop-down menu.
Additionally, dragging the handles to resize the viewport is another handy option to get the exact dimensions you need.
Ever wondered how many media queries sites like YouTube have? You can easily check it by enabling the option to see media queries.
Just click the 3 vertical dots as shown in the media above and enable media queries visibility.
You will see a new panel showing various media query breakpoints which you can click to apply.
Besides this, you can also set breakpoints in your JavaScript code quite easily.
One way to do this is by writing debugger in your code, which will pause the execution when debugger is reached.
console.log('a'); console.log('b'); debugger; console.log('c');
The other way is to go to the Sources tab and then head over to the code file and find the line where you want to pause the execution.
Then you have to click the line number on the left side of your code, which will make a blue icon appear on that line number. That’s it.
DevTools will pause before this line of code is executed.
For more information and to develop web applications using modern front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom web app using JavaScript, please visit our technology page.
Content Source:
Dependency Injection (DI), sometimes referred to as ‘Inversion of Control’, is when an object receives other objects or functions it depends on for part of its functionality. This can be achieved by passing an object through object instantiation with a constructor or with a property setting. This is very common in the world of statically typed languages like Java or C#. There are many popular frameworks built specifically for managing dependencies in the statically typed object-oriented world.
DI allows specific functionality to be loaded at runtime. One of the advantages of being able to change the functionality of an object at runtime is to provide greater flexibility and make our applications more loosely coupled. A very common use case is using mocking during testing. There are some great libraries in Node.js like Sinon that make mocking very easy, but we can accomplish the same task by using DI.
It is very common with testing to substitute code that communicates with a database or a network request with a mock or fake. This is because in a lot of CI/CD workflows the build or testing server may not have access to a database server or a network needed for the actual service. This is an excellent use case for DI to substitute an actual service with a mock or fake service.
There are many different reasons to use DI, but testing is one of the most common reasons.
We have a technique that We have used throughout the years for configuring DI in my applications whether they are statically typed or duct-typed like JavaScript that We like to call ‘Poor Mans Dependency Injection’. With this technique, We usually create default dependent objects if a required object is not passed in on object instantiation.
Lets’ say we have a cart object that needs to calculate a tax rate for a certain location. In a lot of e-commerce systems that kind of data has to be calculated based on the location of the user, with the sales tax being different for every location. We can create a factory function that creates a shopping cart with an injectable function for calculating the tax.
function createCart(settings) { const { taxrepository } = settings; let items = []; function addItemToCart(item) { items.push(item); } function removeItemFromCart(removeThisItem) { items = items.filter((item, index, arr) => { return item.sku !== removeThisItem.sku }); } function getSubTotal() { return items.map(item => item.price * item.quantity) .reduce((accum, item) => accum + item, 0); } function getTotal() { return taxrepository(getSubTotal()) + getSubTotal(); } function getTaxes() { return taxrepository(getSubTotal()); } return Object.freeze({ addItemToCart, removeItemFromCart, getSubTotal, getTotal, getTaxes }); }
If we look at the following example, we are creating an object with functions for adding items to the cart and calculating the totals and subtotals. We have a function that we can pass into our settings constructor object called taxrepository
. We will use this function to calculate our taxes.
Lets’ create a test function for calculating our taxes. We will make this a pure function without any side effects.
function calculateMyTax(subtotal) { return subtotal * 0.11; }
When we instantiate this object with our factory function, we can just pass it into our settings object;
const cart = createCart({ taxrepository: calculateMyTax }); myCart.addItemToCart({ sku: 'DEF456', price: 2.00, quantity: 2 }); myCart.addItemToCart({ sku: 'HIG789', price: 6.00, quantity: 1 }); myCart.addItemToCart({ sku: 'ABC123', price: 12.00, quantity: 1 });
We can now get the subtotal and calculate the taxes.
console.log(`subtotal: ${myCart.getSubTotal()}`); // subtotal: 22 console.log(`taxes: ${myCart.getTaxes()}`); // taxes: 2.42 console.log(`total: ${myCart.getTotal()}`); // total: 24.42
All of the objects that We define, We try to create defaults for whenever an injectable behavior is not included in the constructor. That way if someone is using my object without passing in the needed objects, it will either get an error or a default function if it is missing from the constructor. We can modify the factory function to use a default if no taxrepository
is passed in the settings object.
We also might want to have our factory function fail if the developer calling our function forgets to pass the taxrepository
into the constructor.
if (!settings.hasOwnProperty('taxrepository')) { throw Error(`This function requires a 'taxrepository' to be passed into the contructor!`) }
DI frameworks are extremely popular in the statically typed object-oriented world of Java and .NET development, but there are DI frameworks you can use for JavaScript. One of the frameworks is called di4js, and will work with either Node.js or plain old JavaScript in the browser. Here is an example from the di4js readme;
var Car = function (engine, year) { this.engine = engine; this.year = year; }; Car.prototype.start = function () { this.engine.start(); }; var DieselEngine = function () { this.hp = 0; }; DieselEngine.prototype.start = function () { console.log("Diesel engine with " + this.hp + " hp has been started..."); }; di .autowired(false) .register('dieselEngine') .as(DieselEngine) .withProperties() .prop('hp').val(42); .register('car') .as(Car) .withConstructor() .param().ref('dieselEngine') .param().val(1976); var car = di.resolve('car'); car.start(); // Diesel engine with 42 hp has been started...
This example is from the di4js Github repo
For more information and to develop your web app using front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop your custom website using JS, please visit our technology page.
Content Source:
In the current age of JavaScript, Promises are the default way to handle asynchronous behavior in JavaScript. But how do they work? Why should you understand them very well?
When we make you a promise, you take our word that we will fulfill that promise.
But we don’t tell you when that promise will be fulfilled, so life goes on…
There are two possible scenarios: fulfillment or rejection.
One day, we fulfill that promise. It makes you so happy that you post about it on Twitter!
One day, we tell you that we can’t fulfill the promise.
You make a sad post on Twitter about how we didn’t do what we had promised.
Both scenarios cause an action. The first is a positive one, and the next is a negative one.
Keep this scenario in mind while going through how JavaScript Promises work.
JavaScript is synchronous. It runs from top to bottom. Every line of code below will wait for the execution of the code above it.
But when you want to get data from an API, you don’t know how fast you will get the data back. Rather, you don’t know if you will get the data or an error yet. Errors happen all the time, and those things can’t be planned. But we can be prepared for it.
So when you’re waiting to get a result from the API, your code is blocking the browser. It will freeze the browser. Neither we nor our users are happy about that at all!
Perfect situation for a Promise!
Now that we know that you should use a Promise when you make Ajax requests, we can dive into using Promises. First, we will show you how to define a function that returns a Promise. Then, we will dive into how you can use a function that returns a Promise.
Below is an example of a function that returns a Promise:
function doSomething(value) { return new Promise((resolve, reject) => { // Fake a API call setTimeout(() => { if(value) { resolve(value) } else { reject('The Value Was Not Truthy') } }, 5000) }); }
The function returns a Promise. This Promise can be resolved or rejected.
Like a real-life promise, a Promise can be fulfilled or rejected.
According to MDN Web Docs, a JavaScript Promise can have one of three states:
"- pending: initial state, neither fulfilled nor rejected. - fulfilled: meaning that the operation was completed successfully. - rejected: meaning that the operation failed."
The pending state is the initial state. This means that we have this state as soon we call the doSomething() function, so we don’t know yet if the Promise is rejected or resolved.
In the example, if the value is truthy, the Promise will be resolved. In this case, we pass the variable value in it to use it when we would call this function.
We can define our conditions to decide when to resolve our Promise.
In the example, if the value is falsy, the Promise will be rejected. In this case, we pass an error message. It’s just a string here, but when you make an Ajax request, you pass the server’s error.
Now that we know how to define a Promise, we can dive into how to use a function that returns a Promise:
// Classic Promise doSomething().then((result) => { // Do something with the result }).catch((error) => { console.error('Error message: ', error) }) // Use a returned `Promise` with Async/Await (async () => { let data = null try { data = await doSomething() // Do something with the result } catch(error) { console.error('Error message: ', error) } })();
You can recognize a function that returns a Promise by the .then() method or an await keyword. The catch will be called if there is an error in your Promise. So making error handling for a Promise is pretty straightforward.
Promises are used in a lot of JavaScript libraries and frameworks as well. But the simplest web API is the Fetch API, which you should use for making Ajax requests.
For more information and to develop your web app using front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using JS, please visit our technology page.
Content Source:
Typescript’s 4.2 was just released recently. What awesome features does this release bring? What impact does it have in your daily life as a Developer? Should you immediately update?
Here, we will be going through all the most exciting new features. Here is a summary:
To get an editor with the latest Typescript version use Visual Studio Code Insiders. You can use a plugin alternatively for VS Code.
If you just want to have a play while reading the article you can use the Typescript Playground here. It is a fun and super easy tool to use.
Sometimes TypeScript just doesn’t resolve types properly. It may return the correct types but just not return the correct alias. The alias could be important and shouldn’t be lost along the way.
Let’s check this function:
export type BasicPrimitive = number | bigint; export function divisablePer0(value: BasicPrimitive) { if (value === 0) { return undefined; } return value; } type ReturnAlias = ReturnType<typeof divisablePer0>; // number | bigint | undefined
Notice that an undefined type needs to be added to the method return type as it’s returning undefined on some scenarios.
Before 4.2 the return of type divisablePer0 is number | bigint | undefined. That type is indeed correct but we have lost some information. The alias BasicPrimitive got lost in the process, which is a handy piece of information to have.
If we do the same on TypeScript 4.2 we get the correct alias:
export type BasicPrimitive = number | bigint; export function divisablePer0(value: BasicPrimitive) { if (value === 0) { return undefined; } return value; } type ReturnAlias = ReturnType<typeof divisablePer0>; // BasicPrimitive | undefined
Now the method divisablePer0 has the proper return type: BasicPrimitive | undefined. That makes your code more readable just by upgrading.
In the article about mapped types here we already looked at TypeScript Tuples. As a refresher, let’s revisit the example:
let arrayOptions: [string, boolean, boolean]; arrayOptions = ['config', true, true]; // works arrayOptions = [true, 'config', true]; // ^^^^^ ^^^^^^^^^ // Does not work: incompatible types function printConfig(data: string) { console.log(data); } printConfig(arrayOptions[0]);
However, we forgot to check whether Tuples can use optional elements. Let’s see what the previous example would look like:
let arrayOptions: [string, boolean?, boolean?]; arrayOptions = ['config', true, true]; // works arrayOptions = ['config', true]; // works too arrayOptions = ['config']; // works too function printConfig(data: string) { console.log(data); } printConfig(arrayOptions[0]);
Prior to 4.2 we could even use the spread operator to indicate a dynamic number of elements:
let arrayOptions: [string, ...boolean[]]; arrayOptions = ['config', true, true]; // works arrayOptions = ['config', true]; // works too arrayOptions = ['config']; // works too function printConfig(data: string) { console.log(data); } printConfig(arrayOptions[0]);
In this new TypeScript, version Tuples become more powerful. Previously, we could use the spread operator but we couldn’t define the last element types.
let arrayOptions: [string, ...boolean[], number]; arrayOptions = ['config', true, true, 12]; // works arrayOptions = ['config', true, 12]; // works too arrayOptions = ['config', 12]; // works too function printConfig(data: string) { console.log(data); } printConfig(arrayOptions[0]);
Note that something like this is invalid:
let arrayOptions: [string, ...boolean[], number?];
An optional element can’t follow a rest element. However, note that …boolean[] does accept an empty array, so that Tuple would accept [string, number] types.
Let’s see that in detail in the following example:
let arrayOptions: [string, ...boolean[], number]; arrayOptions = ['config', 12]; // works
The in operator is handy to know if a method or a property is in an object. However, in JavaScript, it will fail at runtime if it’s checked against a primitive.
Now, when you try to do this:
"method" in 23 // ^^ // Error: The right-hand side of an 'in' expression must not be a primitive.
You’ll get an error telling you explicitly what’s going on. As this operator has been made stricter this release might introduce breaking changes.
--noPropertyAccessFromIndexSignature
Yet another compiler configuration that’s always interesting. In TypeScript, you can access properties using the bracketed element syntax or the dot syntax like JavaScript. That accessor is possible when the key is a string.
interface Person { name: string; } const p: Person = { name: 'Max }; console.log(p.name) // Max console.log(p['name']) // Max
There’s a situation that has led to explicit property miss typing:
interface Person { name: string; [key: string]: string; } const p: Person = { name: 'Max }; console.log(p.namme) // undefined console.log(p['namme']) // undefined
Note how we are accessing the wrong property namme but because it fits the [key: string] implicit one, TypeScript won’t fail.
Enabling –noPropertyAccessFromIndexSignature will make TypeScript look for the explicit property when using the dotted syntax.
interface Person { name: string; [key: string]: string; } const p: Person = { name: 'Max' }; console.log(p.namme) // ^^^^^^^^ // Error console.log(p['namme']) // works fine
It’s not part of the strict configuration as this might not suit all developers and codebases.
Template literal types were introduced in 4.1 and here they got smarter. Previously, you couldn’t define a type template usage template literals.
type PropertyType = `get${string}`; function getProperty(property: PropertyType, target: any) { return target[property]; } getProperty('getName', {}); // works const propertyName = 'Name'; const x = `get${propertyName}`; getProperty(x, {}); // ^^^ // Error: Argument of type 'string' is not assignable to parameter of type '`get${string}`'
The core problem is that string expressions are resolving to type string which leads to this type of incompatibility:
const x = `get${propertyName}`; // string
However, with 4.2, template string expressions will always start out with the template literal type:
const x = `get${propertyName}`; // getName
TypeScript’s uncalled function checks apply within && and || expressions. Under –strictNullChecks you will check the following error now:
function isInvited(name: string) { return name !== 'Robert'; } function greet(name: string) { if (isInvited) { // ^^^^^^^^^ // Error: // This condition will always return true since the function is always defined. // Did you mean to call it instead? return `Welcome ${name}`; } return `Sorry you are not invited`; }
Sometimes it can be quite challenging to work out where the Typescript file definitions are pulled from. It’s sometimes a trial and error process.
It’s now possible to get a deeper insight into what’s going on, making the compiler more verbose, using the following:
tsc --explainFiles
Let’s see the result:
It is an awesome feature that will help you understand further Typescript’s internals.
For more information and to develop web application using TypeScript, Hire TypeScript Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using TypeScript, please visit our technology page.
Content Source:
TypeScript 4.0 is a major milestone in the TypeScript programming language and has currently leapfrogged 3.9 to become the latest stable version. In this post, we’ll look at the new features TypeScript 4.0 offers.
To get started using 4.0, you can install it through NuGet or via NPM:
npm i typescript
You can test the code using the TypeScript playground or a text editor that supports TypeScript. I recommend using Visual Studio Code, you can get set up instructions here.
In a nutshell, we can say TypeScript is strongly typed JavaScript. This means that it requires developers to accurately specify the format of their data types, consequently, it allows the compiler to catch type errors at compile time and therefore, give a better developer experience.
This process of accurately specifying the format of data types is known as type declaration or type definitions — it is also called typings or simple types.
With this feature, TypeScript gives types to higher-order functions such as curry, concat, and apply. These are functions that take a variable number of parameters.
Consider a small contrived example of the concat function below:
function simpleConcat(arr1, arr2) { return [...arr1, ...arr2]; } console.log(simpleConcat([1,2,3], [5,6])) // [1, 2, 3, 5, 6]
There is currently no easy way to type this in TypeScript. The only typing strategy available currently is to write overloads.
Function or method overloading refers to a feature in TypeScript that allows us to create multiple functions having the same name but a different number of parameters or types.
Consider this:
function concat1<T>(arr1: [T], arr2: []): [T] { return [...arr1, ...arr2] } function concat2<T1, T2>(arr1: [T1, T2], arr2: []): [T1, T2] { return [...arr1, ...arr2] }; function concat6<T1, T2, T3, T4, T5, T6>(arr1: [T1, T2, T3, T4, T5, T6], arr2: []): [T1, T2, T3, T4, T5, T6] { return [...arr1, ...arr2] } function concat7<T1, T2, T3, T4, T5, T6, A1, A2, A3, A4>(arr1: [T1, T2, T3, T4, T5, T6], arr2: [A1, A2, A3, A4]): [T1, T2, T3, T4, T5, T6, A1, A2, A3, A4] { return [...arr1, ...arr2] } console.log("concated 1", concat1([1], [])) console.log("concated 2", concat2([1,2], [])) console.log("concated 6", concat6([1,2,3,4,5,6], [])) console.log("concated 10", concat10([1,2,3,4,5,6], [10, 11, 12, 13]))
From the example above we can see that the number of overloads increases as the number of items in the array increases which is suboptimal. In concat6 we had to write 6 overloads even when the second array is empty and this quickly grew 10 overloads in concat10 when the second array had just 4 items.
Also, we can only get correct types for as many overloads as we write.
TypeScript 4.0 comes with significant inference improvements. It allows spread elements in tuple types to be generic and to occur anywhere in the tuple.
In older versions, REST element must be last in a tuple type. And TypeScript would throw an error if this were not the case:
// Tuple speard items are generic function concatNumbers<T extends Number[]>(arr: readonly [Number, ...T]) { // return something } // spread occuring anywhere in the tuble valid in 4.0 beta. type Name = [string, string]; type ID = [number, number]; type DevTuples = [...Name, ...Numbers]
Given these two additions, we can write a better function signature for our concat function:
type Arr = readonly any[]; function typedConcat<T extends Arr, U extends Arr>(arr1: T, arr2: U): [...T, ...U] { return [...arr1, ...arr2]; } console.log("concated", typedConcat([1,2,3,4,5], [66,77,88,99]))
This is a pithy addition to TypeScript aimed at improving code readability.
Consider the code below:
type Period = [Date, Date]; // Example 1 older version type Period = [StartDate: Date, EndDate: Date]; // Example 2 4.0 beta function getAge(): [birthDay: Date, today: Date] { // ... }
Previously, TypeScript developers use comments to describe tuples because the types themselves (date, number, string) don’t adequately describe what the elements represent.
From our small contrived example above, “example 2” is way more readable because of the labels added to the tuples.
When labelling tuples all the items in the tuples must be labelled.
Consider the code below:
type Period = [startDate: Date, Date]; // incorrect type Period = [StartDate: Date, EndDate: Date]; // correct
In TypeScript 4.0, we can now use control flow analysis to determine the types of properties in classes when noImplicitAny is enabled. Let’s elaborate on this with some code samples.
Consider the code below:
// Compile with --noImplicitAny class CalArea { Square; // string | number constructor(area: boolean, length: number, breadth: number) { if (!area) { this.Square = "No area available"; } else { this.Square = length * breadth; } } }
Previously, the code above would not compile if noImplicitAny is enabled. This is because property types are only inferred from direct initializations, so their types must either be defined explicitly or using an initial initializer.
However, TypeScript 4.0 can use control flow analysis of this.Square assignments in constructors to determine the types of Square.
Currently, in JavaScript, a lot of binary operators can be combined with the assignment operator to form a compound assignment operator. These operators perform the operation of the binary operator on both operands and assigned the value to the left operand:
// compound operators foo += bar // foo = foo + bar foo -= bar // foo = foo - bar foo *= bar // foo = foo * bar foo /= bar // foo = foo/bar foo %= bar // foo = foo % bar
The list goes on but with three exceptions:
|| // logical or operator && // logical and operator ?? // nullish coalescing operator
TypeScript 4.0 beta would allow us to combine these three with the assignment operator thus forming three new compound operators:
x ||= y // x || (x = y) x &&= y // x && (x = y) x ??= y // x ?? (x = y )
Previously, when we use the try … catch statement in TypeScript, the catch clause is always typed as any, consequently, our error-handling code lacks any type-safety which should prevent invalid operations. I will elaborate with some code samples below:
try { // ... }catch(error) { error.message error.toUpperCase() error.toFixed() // ... }
From the code above we can see that we are allowed to do anything we want — which is really what we don’t want.
TypeScript 4.0 aims to resolve this by allowing us to set the type of the catch variable as unknown. This is safer because it’s meant to remind us to do a manual type checking in our code:
try { // ... }catch(error: unknown) { if(typeof error === "String") { error.toUpperCase() } if(typeof error === "number") { error.toFixed() } // ... }
TypeScript already supports jsxFactory compiler option, this feature, however, adds a new compiler option known as jsxFragmentFactory which enables users to customize the React.js fragment factory in the tsconfig.json:
{ "compilerOptions": { "target": "esnext", "module": "commonjs", "jsx": "react", // React jsx compiler option "jsxFactory": "createElement", // transforms jsx using createElement "jsxFragmentFactory": "Fragment" // transforms jsx using Fragment } }
The above tsconfig.json configuration transforms JSX in a way that is compatible with React thus a JSX snippet such as <article/> would be transformed with createElement instead of React.createElement. Also, it tells TypeScript to use Fragment instead of React.Fragment for JSX transformation.
TypeScript 4.0 also features great performance improvements in –build mode scenarios and also allows us to use the –noEmit flag while still leveraging –incremental compiles. This was possible in older versions.
In addition, there are several editor improvements such as @deprecated JSDoc annotations recognition, smarter auto-imports, partial editing mode at startup (which aimed to speed up startup time).
For more information and to develop web application using TypeScript, Hire TypeScript Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using TypeScript, please visit our technology page.
Content Source:
Apollo Client 3 offers a few new features, including package rearrange changes and more caching features. Let’s proceed to take a look at how to use the latest features from Apollo Client 3.
The InMemoryCache API has expanded features. They include the eviction of objects and fields, garbage collection, types and fields configuration, and pagination helpers.
Let’s explore these changes by installing the @apollo/client package with its dependencies by running:
npm i @apollo/client graphql react
We can add the InMemoryCache into our Apollo Client by writing:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client"; const cache = new InMemoryCache(); const client = new ApolloClient({ uri: "https://graphqlzero.almansi.me/api", cache }); client .query({ query: gql` { user(id: 1) { id name } } ` }) .then(console.log);
The client is created with the cache option, which we set to the InMemoryCache; the cached items will be in memory. Once we’ve done that, we can use the new InMemoryCache features that come with Apollo Client 3.
We can evict the cached items by calling:
cache.evict();
We can optionally pass in the cached object’s ID by writing:
cache.evict({ id: 'user' })
We can also add a field property of the object like so:
cache.evict({ id: 'user', fieldName: 'name' })
The cache.gc method lets us do garbage collection on cached items. The object is determined to be reachable by tracing from the root to all the child references. Normalized objects that aren’t visited are removed.
To clear the unreachable cached items, we just call:
cache.gc();
Garbage collection can also be configured to retain some items. To retain the object with the ID ‘user’, for instance, we can write;
cache.retain({ id: 'user' })
We can configure how to deal with dangling references. When an object is evicted from the cache, it might have objects that have other cached objects. Apollo Client preserves these references because they may still be used later.
We can change how these references are dealt with by using a custom read function. To do so, we would write:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client"; const cache = new InMemoryCache({ typePolicies: { Query: { fields: { ruler(existingRuler, { canRead, toReference }) { return canRead(existingRuler) ? existingRuler : toReference({ __typename: "user", name: "Apollo" }); } } }, user: { keyFields: ["name"], fields: { offspring(existingOffspring, { canRead }) { return existingOffspring ? existingOffspring.filter(canRead) : []; } } } } }); const client = new ApolloClient({ uri: "https://graphqlzero.almansi.me/api", cache }); client .query({ query: gql` { user(id: 1) { id name } } ` }) .then(console.log);
We set the ruler of the cache to our own ruler function. We determine what references can be read.
If there’s an existing cache ruler, then we use it; otherwise, we get the item with toReference. The offspring method returns the objects where canRead returns true. This way, we know we can read those items.
We can create our own local field within the InMemoryCache object.
For instance, we can write:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client"; const cache = new InMemoryCache({ typePolicies: { User: { fields: { age: { read(_, { variables }) { return Math.random() * 100; } } } } } });
We created a local field with name age. This way, we can include the field in our query like the loading state and the networkStatus. variables have the fields from the query. It also has the caching data.
It’s just a getter that returns a random number:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client"; const cache = new InMemoryCache({ typePolicies: { User: { fields: { age: { read(_, { variables }) { return Math.random() * 100; } } } } } }); const client = new ApolloClient({ uri: "https://graphqlzero.almansi.me/api", cache }); client .query({ query: gql` { user(id: 1) { id name age @client } } ` }) .then(console.log);
We get the age field with age @client. The @client keyword distinguishes local fields from fields that are retrieved from the API.
Reactive variables is the new feature from Apollo Client 3.0 onwards. To create one, we use the makeVar method from the @apollo/client package. For instance, to create a children reactive variable, we can write:
import { makeVar } from "@apollo/client"; const children = makeVar(["jane", "mary"]);
It returns a function that has the value of the reactive variable. To call it and get the value, we can write:
console.log(children());
The console log should read:
["jane", "mary"]
Reactive variables are useful for storing local state outside of the Apollo Client cache. This is different from local states and cached items, which are retrieved from the cache. Modifying a reactive variable automatically triggers an update of all active queries that depend on the variable.
We can also store local state with reactive variables. To do that, we can write:
import { ApolloClient, InMemoryCache, gql, makeVar } from "@apollo/client"; const age = makeVar(Math.random() * 100); const cache = new InMemoryCache({ typePolicies: { User: { fields: { age: { read(_, { variables }) { return age(); } } } } } }); const client = new ApolloClient({ uri: "https://graphqlzero.almansi.me/api", cache }); client .query({ query: gql` { user(id: 1) { id name age @client } } ` }) .then(console.log);
Above, we created the age reactive variable, and we read it into the local state by returning it in the read method. Then we can query age like we do with other local states. Now, whenever our query changes, we’ll see a new value of age returned as well.
To update the reactive variable, we just pass in a new value, like so:
import { makeVar } from "@apollo/client"; const age = makeVar(Math.random() * 100); console.log(age()); age(Math.random() * 100); console.log(age());
We pass in a new value to the function returned by makeVar to update the value. Now both console logs should show different values.
We can define our own cache field policy so that we can read them in a way that’s different from what’s in the API.
For instance, we can write:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client"; const cache = new InMemoryCache({ typePolicies: { User: { fields: { name: { read(name) { return name.toUpperCase(); } } } } } }); const client = new ApolloClient({ uri: "https://graphqlzero.almansi.me/api", cache }); client .query({ query: gql` { user(id: 1) { id name } } ` }) .then(console.log);
We created a type policy for the User type. fields has the fields we want to modify when reading, and we want the value of name to be upper-case.
So we make the name’s read method return the upper-case name. Now the console.log call in the then method should have the data field with user.name inside it being upper-case.
We can use this for many other applications, like setting default field values, transforming lists, changing field values, pagination, and much more.
Apollo Client 3 comes with many changes to caching, including the ability to clear cache data. We can also add local fields and change the ways normal fields are retrieved with cache policy.
For more information and to develop web application using Front-End JS, Hire Front-End Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop custom web apps using Front-End JS, please visit our technology page.
Content Source:
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2024 — HK Infosoft. All Rights Reserved.
© 2024 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap