Using localStorage with React Hooks in TypeScript

Using localStorage with React Hooks in TypeScript

Source code: github.com/Arpitha-Rajeev1/vite-card-select..

LocalStorage is used to store data in the key-value pair using setItem() that has no expiration time that is data is not deleted even when the browser gets closed. The stored data can be accessed using getItem(). Other methods of localStorage are removeItem() and clear() to remove the item from localStorage by passing the key and to clear the localStorage respectively. The example snippet below depicts the use of localStorage.

const person = {
    name: "John Doe",
    age: "24",
}

//sets the person object to a key named 'user'
window.localStorage.setItem('user', JSON.stringify(person)); 
//get the value stored in localStorage using its key 'user'
window.localStorage.getItem('user'); 
//removes the key 'user' and its value from the localStorage
window.localStorage.removeItem('user');
//localStorage becomes empty after clearing
window.localStorage.clear();

Many a time we want to select items and retrieve them indefinitely. This can be in an E-commerce app where the user selects multiple items among the displayed items. In this article, I am using useState and useEffect hook, react-bootstrap, react-vite, TypeScript, localStorage. We will start with creating a new react app using vite as it is super fast. We will use React and TypeScript. Then we will install react-bootstrap and will add import 'bootstrap/dist/css/bootstrap.min.css'; in main.tsx file.

App.tsx will contain the card component from react-bootstrap. Here, the red color border will appear when the user selects that particular card and we have a function toggleSelect() to select and deselect the card. map is used to retrieve the elements from the response we get by calling API.

1.PNG

We initialize the state variables along with the types. We are using a dummy API from JSON placeholder to get some sample responses, a count variable is an object that stores the response and arr is a number array. Since, localStorage only stores strings, we use JSON.stringify() to store an array or object. If we try to directly store a JavaScript object in the localStorage without converting it to string, then the value won't be stored and it returns [object, object] which is a string representation of an object instance and its value is never read. Similarly, when we want to read the value stored in localStorage we use JSON.parse() that converts a string to JavaScript object.

2.PNG

Finally, we have our toggleSelect() function to select and deselect the cards. Whenever we use a state variable to store an array, we must use the spread operator while updating the state. The spread operator will store the previous values in an array and appends the new value finally updating the array. We are using the filter method to remove the elements.

3.PNG

The UI looks like this:

4.PNG