Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, November 7, 2023

Debounce in Javascript and React

    Debounce is a technique used to improve the performance of frequently executed actions, by delaying them, grouping them, and only executing the last call.

    Imagine, Say for example, You need a search input that automatically queries results as you type.

     You don't want to call the backend or API's with every keystroke, instead you only observe the final value. This is the perfect use for the debounce function, and in fact, it's the most common one.

Define basic debounce function with Javascript

Debounce is implemented using a timer, where the action executes only after the timeout. If the action is repeated before the timer has expires, we restart the timer. 

 

function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}

  In the debounce function:

  • func is the original function you want to debounce.
  • delay is the time in milliseconds that you want to wait after the last call before invoking the original function. 

Implement the debounce function 

    Create a function that accepts a function to debounce and the timeout delay as arguments.


const updateOptions = debounce(query => {
fetch(`https://dummyjson.com/products/search?q=${query}`)
.then(res => res.json())
.then(data => setOptions(data))
}, 1000)
input.addEventListener("input", e => {
updateOptions(e.target.value)
)}

Implement the debounce function with React


export default function SearchBox() {
const [search, setSearch] = React.useState("");
const [result, setResult] = React.useState([]);
const handleChange = (e) => {
setSearch(e.target.value);
};

let timeout;

const handleSearch = async (query) => {
setResult([]);
if (query.length < 3) {
return null;
}
const response = await fetch(
`https://dummyjson.com/products/search?q=${query}`
);
const { products } = await response.json();
setResult(products);
};

React.useEffect(() => {
clearTimeout(timeout);
timeout = setTimeout(() => {
handleSearch(search);
}, 500);
return () => clearTimeout(timeout);
}, [search]);

return (
<>
<div className="mb-3 m-11">
<div className="relative mb-4 flex w-full flex-wrap items-stretch">
<form>
<label
htmlFor="default-search"
className="mb-2 text-sm font-medium text-gray-900 
sr-only dark:text-white"
>
Search
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 flex items-center 
pl-3 pointer-events-none">
<svg
className="w-4 h-4 text-gray-500 dark:text-gray-400"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 20 20"
>
<path
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m19 19-4-4m0-7A7 7 0 1 1 1 8a7 7 0 0 1 14 0Z"
/>
</svg>
</div>
<input
type="search"
id="default-search"
className="block w-full p-4 pl-10 text-sm text-gray-900
 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 
focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 
dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 
dark:focus:border-blue-500"
placeholder="Search Mockups, Logos..."
value={search}
onChange={handleChange}
/>
</div>
</form>
</div>
</div>

<div className="mb-3 m-11">
{result.map((item) => (
<div className="text-xl">{item.title}</div>
))}
</div>
</>
);
}


the  useEffect runs every time the input value changes, after which there is a delay of 500 milliseconds, then the value result is updated with search value.

The Result will be 


 

Happy Coding...😀

Monday, February 17, 2014

How to use local storage for JavaScript

Creating an to-do app is usually the first application you learn how to build in JavaScript but the problem with all those apps is that when you reload the page all those to-do’s are gone. There is a simple solution though, and that’s to use local storage.

The good thing about local storage is that you can save those bits of data to the user’s computer so that when they reload the page all of their todo’s will still be there and local storage is actually quite simple when it comes to saving the data and making it available on the page.

What is local storage?

Local storage is a part of web storage, which itself is part of the HTML5 specification. There are two options for storing data in the specification:
  • Local Storage: stores data with no expiration date and this is the one we will be using because we want our to-do’s to stay on the page for as long as possible.
  • Session Storage: only saves the data for one session so if the user closes the tab and reopens it all their data will be gone.
In simple terms, all that web storage does is store named key/value pairs locally and unlike cookies this data persists even if you close your browser or turn off your computer.

The HTML

If we think about a to-do list what we will need is :
  • An input to place our to-do.
  • An input button to add our to-do.
  • A button to clear all the to-do’s.
  • A placeholder unordered list where our to-do’s will be placed in list items.
  • And finally we need a placeholder div to show an alert when you try to enter an empty to do.
So our HTML should look something like this:

<section>
 
 <form id="form" action="#" method="POST">
 
  <input id="description" name="description" type="text" />
 
  <input id="add" type="submit" value="Add" />
 
  <button id="clear">Clear All</button>
 
 </form>

 <div id="alert"></div>
 
 <ul id="todos"></ul>
</section>


It’s a pretty standard placeholder HTML and with our javascript we can fill all this up with dynamic content. Since we will be using jQuery in this example you should also include it in your HTML document.

The JavaScript

If we think about the structure of a simple to-do app the first thing we need to do is check for when the user clicks on add button and check if the input has an empty value, like so:
$('#add').click( function() {
   var Description = $('#description').val();
   //if the to-do is empty
   if($("#description").val() == '') {
    $('#alert').html
("<strong>Warning!</strong> You left the to-do empty");
    $('#alert').fadeIn().delay(1000).fadeOut();
    return false;
   }

All we did was check for a click on the add button and run a simple 
test to check if the user filled the input with something. If not, the 
alert div fades in and stays for 1000ms and then fades out. Finally we 
return false so that the browser doesn’t read the rest of the script and
 still add the list item.

The next thing we need to do is insert a list item with the value in the input and we will prepend this so that when the user adds a to-do it will always go to the beginning of the list and then save that list item to local storage, like so:
// add the list item
   $('#todos').prepend("<li>" + Description + "</li>");
   // delete whatever is in the input
   $('#form')[0].reset();
   var todos = $('#todos').html();
   localStorage.setItem('todos', todos);
   return false;
});

As you can see it’s pretty standard jQuery and when it comes to local
 storage we need to save a key and a value. The key is a name we set for
 ourselves and in this case i just called it ‘todos’ and then we need to
 specify what we actually want to save, and in this case that is all the
 HTML that is placed inside the todos unordered list. As you can see we 
just grabbed that using jQuery and we finally returned false so that the
 form doesn’t submit and our page doesn’t reload.

Our next step is to check if we have something on local storage already saved in our machine and if we do we need to place that in the page, so since we gave our key the name todos we need to check for its existence like so:
// if we have something on local storage place that
if(localStorage.getItem('todos')) {
$('#todos').html(localStorage.getItem('todos'));
}

We used a simple if statement to check and then we merely got what we
 have on local storage and place that as the HTML of the to-do’s 
unordered list.

If you test our simple app and we reload the page we see that it’s already working and all we have left is to create the function for when the user chooses to clear all the to-do’s; when that happens we will clear all local storage, reload the page for our changes take effect, and then return false to prevent the hash in front of the url like so:
// clear all the local storage
$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});

With this done we have our app fully working. The full code looks like this:
$('#add').click( function() {
   var Description = $('#description').val();
  if($("#description").val() == '') {
    $('#alert').html
("<strong>Warning!</strong> You left the to-do empty");
    $('#alert').fadeIn().delay(1000).fadeOut();
    return false;
   }
   $('#todos').
prepend("<li><input id='check' name='check' type='checkbox'/>" 
+ Description + "</li>");
   $('#form')[0].reset();
   var todos = $('#todos').html();
   localStorage.setItem('todos', todos);
   return false;
});
if(localStorage.getItem('todos')) {
$('#todos').html(localStorage.getItem('todos'));
}
$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});

Store an Array in localStorage
localStorage only supports strings. Use JSON.stringify() and JSON.parse(). for store and retrieve the array.

var names = [];
names[0] = prompt("New member name?");
localStorage["names"] = JSON.stringify(names);
//...
var storedNames = JSON.parse(localStorage["names"]);

Browser support

The support for web storage is pretty good for an HTML5 specification; it is supported by all the major browsers and even IE8, so the only thing you might need to be wary of is IE7 if you’re still supporting that.

Conclusion

Local storage in small apps like this can very welcome substitutes for databases. Storing small amounts of data doesn’t need to be complex.

Source From: http://www.webdesignerdepot.com

Thursday, July 18, 2013

Some useful tools for web developers

1. HTML and CSS Table Border Style Wizard
http://www.somacon.com/p141.php

2. oAuth End Points Cheat Sheet
http://www.cheatography.com/kayalshri/cheat-sheets/oauth-end-points/

3. HTML Compression Tool
http://www.textfixer.com/html/compress-html-compression.php

4. CSS Compression Tool
http://www.codebeautifier.com/#skip

5. Online Code Beautifier for JavaScript, HTML, CSS and PHP
http://ctrlq.org/beautifier/

6. Online JavaScript beautifier
http://jsbeautifier.org/

7. CSS Drive Gallery- CSS Compressor
http://www.cssdrive.com/index.php/main/csscompressor/

8. 10 useful .htaccess snippets to have in your toolbox | CatsWhoCode.com
http://www.catswhocode.com/blog/10-useful-htaccess-snippets-to-have-in-your-toolbox

9. Google URL Shortener
http://goo.gl/

10. Google oAuth2.0 Playground
https://developers.google.com/oauthplayground/

11. oAuth End Points Cheat Sheet
http://www.cheatography.com/kayalshri/cheat-sheets/oauth-end-points/