Error reading Localstorage array

Asked

Viewed 27 times

2

Hello, I have an array and the user can shuffle the order of the items:

Blusas = ['verde','azul','amarela','rosa','laranja','preta','roxa','vermelha',]

After shuffling, this is the update capture code, turning the array into a string:

window.localStorage.setItem('Blusas', JSON.stringify(this.Blusas))

And this is the code to save the update on Oninit:

this.Blusas = localStorage.getItem('Blusas');

However, I get this error flagged in "this.Blouses":

Type 'string' is not Assignable to type 'string[]'

Can anyone help me? I can’t find a solution anywhere.

  • is a little confused, where it gives the error, on set or get? "And this is the code to save the update on Oninit" this "saved" code I think would be "read" right? I tested the set/get in the browser and it works, wouldn’t that be a problem with this? There’s no code at all

  • That’s right, reading code. From what I search, it’s as if "this.Blusas" is not recognized as a string and therefore cannot be stored. I tried to switch to "Blouses: string = ['green','blue','yellow','orange','black','purple','red'] but the array is still not recognized as a string.

  • Some suggestions to improve your code... 1. Name properties and variables in camelCase. I mean, rename Blusas for blusas. 2. Avoid accessing localStorage this way. The nicest thing would be for you to encapsulate access through a service, which would bring several advantages. Greater adherence to SRP, greater abstraction, decoupling, ease of testing, etc.

1 answer

2


Blusas is the type string[]. When you call localStorage.getItem('Blusas'), is returned the "stringificada" version of the sweater array that you saved in the Storage location. In other words - you are trying to mark a string in an array of strings.

To fix, just parse the string back to its array form.

this.Blusas = JSON.parse(localStorage.getItem('Blusas'))
  • 1

    Thank you very much! Solved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.