Change Typescript Function to retrieve JSON data from Session Storage instead of a JSON file

Change TypeScript Function to retrieve JSON data from Session Storage instead of a JSON file

When working with TypeScript, it is common to retrieve JSON data from a JSON file. However, there may be scenarios where you need to retrieve the JSON data from Session Storage instead. In this blog post, we will explore how to modify a TypeScript function to achieve this.
Let’s assume you have a TypeScript function called getJsonData that currently retrieves JSON data from a file:


function getJsonData() {
  return fetch('data.json')
    .then(response => response.json())
    .then(data => {
      console.log(data);
    })
    .catch(error => {
      console.error('Error:', error);
    });
}
  

To change this function to retrieve JSON data from Session Storage, you can modify it as follows:


function getJsonData() {
  const jsonData = sessionStorage.getItem('jsonData');
  if (jsonData) {
    return Promise.resolve(JSON.parse(jsonData));
  } else {
    return Promise.reject('JSON data not found in Session Storage');
  }
}
  

In the modified function, we first check if the JSON data exists in Session Storage using the getItem method. If the data exists, we parse it using JSON.parse and return a resolved Promise with the parsed data. If the data does not exist, we return a rejected Promise with an error message.
Now, let’s see an example of how to use this modified function:


getJsonData()
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
  

In this example, we call the getJsonData function and handle the returned Promise. If the Promise is resolved, we log the retrieved JSON data. If the Promise is rejected, we log the error message.
By modifying the TypeScript function, you can easily retrieve JSON data from Session Storage instead of a JSON file. This can be useful in scenarios where you need to store and retrieve data locally within the browser.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *