When refreshing in Angular, the Local Storage service returns an undefined value for the getItem

In an attempt to store a value in localStorage and retrieve it upon refresh, I have developed a local-storage service to set the value by calling the service.

When trying to retrieve the value on refresh, I found that my appComponent's ngOnInit method appeared as follows:

ngOnInit() {
// Service which returns undefined
console.log(this.ls.getLocalStorage('test'))

// local which returns value...
console.log(localStorage.getItem('test'));

}

Within my local-storage-service, the code is structured like so:

getLocalStorage(k) {
    console.log(k);
    localStorage.getItem(k);
}

Oddly enough, the first console log in my onInit function returns 'undefined' while the second one correctly displays the value. Why does this discrepancy exist and is there a potential resolution?

Any insights would be appreciated. Thank you.

Answer №1

To ensure your function returns a value, be sure to include the return keyword at the end of your function code block.

fetchDataFromLocalStorage(key) {
    console.log(key);
    return localStorage.getItem(key);
}

Answer №2

It appears that you forgot to include a return statement in your code

Your function should be structured as follows:

fetchData(key) {
    return localStorage.getItem(key);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing Angular Components with Jasmine and Karma: When handling the 'onChange' event, the changeEvent parameter of type MatRadioChange should not be void and must be assigned to a parameter of type

Hey there, I was working on a test for a call where I am using to emit the event: onChange(eventName: MatRadioChange): void { this.eventName.emit(eventName.value); } Here is the test I have written for it: describe('onChange', (eventName: ...

Exploring a Firestore collection to extract data fields for storage and utilization

I'm currently facing a challenge while attempting to access my Firestore collection and iterate through all documents to extract the valenceId field in each document. Despite trying various approaches, I keep encountering an error message stating: "c ...

Trouble with Angular2: Socket.io event not refreshing the view

I attempted to update my view upon receiving a socket event. This is what my component code looks like: constructor(private _zone: NgZone){ this.socket = io.connect('http://localhost:3000'); this.socket.on('someEvent', function ...

Display additional json elements as you scroll down

The total number of JSON objects is 100. Initially display the first set of 20 objects. As you scroll down, the next 20 objects will be shown. This process continues until all 100 objects have been displayed. ...

Having trouble getting Angular PWA configured properly

I've been trying to configure my Angular project as a progressive web app following the official documentation. However, I encountered an error when attempting to run it on my local server. The error message displayed is "GET /" Error (404): "Not foun ...

Manually Enroll Node Module

Question: I am tackling a challenge in my TypeScript project where I need to interact with multiple APIs that are not available locally on my computer, but exist on the web. The code compiles without issues on my local machine as I have all the API declar ...

Avoid using propTypes for props verification

Looking for a solution to handle multiple props on a button: interface buttonProps { secondary?: boolean; tertiary?: boolean; width?: number; children?: any; icon?: string; } If the button includes an icon without any children, how can ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...

What is the best way to view and understand code from imported angular modules within vs-code?

When I [ctrl]-click on a type in VS Code, I can view the following snippet of "code" (from a compiled Angular class/module): export declare class Record extends HashMap { readonly id: number; constructor(id: number); } export declare class HashMa ...

Unable to utilize React Icons component as an object value in typescript

Currently, as I develop my personal website using typescript and react, I am faced with an issue in the footer section. I have an array of objects with url and icon properties that I map through to display different icons on each iteration. Initially, this ...

Injecting properties into higher order functions in Typescript allows for the dynamic customization

I'm curious about the process of composing functions that take an object as the sole argument, where each higher order function adds a property. For instance, I have a function that takes a context as input. I would like to wrap this function with a w ...

How to set a custom height for Mat-form-field in Angular 8 using pixel values

Is there a way to adjust the height of mat-form-field when using appearance="outline" to a specific pixel measurement, such as 40px (or any other value required by the UX team in the future)? I need to decrease the size of the mat-form-field. How can this ...

Updating Elements in an Array Using JavaScript is Not Functioning as Expected

In my Angular application, I have included some lines of TypeScript code which involve Boolean variables in the constructor and an array of objects. Each object in this array contains input variables. selftest: boolean; failed: boolean; locoStateItem ...

Angular 2: Export Data to CSV and Download

My backend is built in a Spring Boot application where I am returning a .csv file. @RequestMapping(value = "/downloadCSV") public void downloadCSV(HttpServletResponse response) throws IOException { String csvFileName = "books.csv"; ...

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...

Determine the data type of a property by referencing the data type of another property within an array of objects using TypeScript

I am working with a specific type of interface called Route that consists of name and path properties. interface Route { name: string, path: string } const routes = [ { name: "first", path: "/first" }, ...

Dealing with enum values in Jest tests when using Prisma can be tricky. The error message "Group[] not assignable to

Here is an example of my prisma postgresql schema: model User { id Int @id @default(autoincrement()) uuid String @db.Uuid createdat DateTime @default(now()) @db.Timestamp(6) updatedat DateTime @updatedAt first ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Looking to display a single Angular component with varying data? I have a component in Angular that dynamically renders content based on the specific URL path

I have a component that dynamically renders data based on the URL '/lp/:pageId'. The :pageId parameter is used to fetch data from the server in the ngOnInit() lifecycle hook. ngOnInit(){ this.apiHelper.getData(this.route.snapshot.params.pageId) ...

How can I postpone the initialization of ngOnInit in Angular 7?

While attempting to send and retrieve data for display, I encountered an issue where the component initializes before the new data is added to the server. This results in a missing element being displayed. Is there a way to delay the initialization proce ...