3

I have fieldObj which I need frequently. It comes from database. I want to store it in localStorage.

below is the code I wrote which fetch fieldObj from database if localStorage don't have it.

When I try to access the json data stored in localStorage it just shows

[object Object]

code is treating fieldObj of localStorage as string.

I need to access key values pairs stored in fieldObj.

<script>
export default {
  data() {
    return {
      fields: JSON,
    }
  },
  created() {
    if (!localStorage.getItem('field-obj')) {
      axios
        .get('/api/u/record/', {
          withCredentials: true,
        })
        .then((response) => {
          response.data.forEach((el) => {
            if (el.COLUMN_TYPE == 'int') el.COLUMN_TYPE = 'number'
          })
          const fieldObj = response.data[0].fieldObj[0]
          this.fields = fieldObj
        })
        .then(() => {
          localStorage.setItem('field-obj', this.fields)
        })
    } else {
      console.log(new Object(localStorage.getItem('field-obj')))
      // console.log(localStorage.getItem('field-obj')[0].username)
    }
  },
}
</script>
8
  • 1
    Try to wrap the thing that you want to display into a JSON.parse(JSON.stringify(yourObject)) to inspect the variable. There is probably an object down there and not a string or alike. Commented May 5, 2022 at 12:53
  • do you mean JSON.parse(JSON.stringify(localStorage.getItem('field-obj'))) ? Commented May 5, 2022 at 12:59
  • when it fetch fieldObj from database it gives {case index: 'varchar(14)', next visit: 'date', patient name: 'varchar(30)', prescription: 'varchar(255)'} Commented May 5, 2022 at 13:05
  • 1
    Yes for the first question. So if you store an object in your localStorage, you will get an object back. Hence something like localStorage.getItem('field-obj').prescription may be needed. Commented May 5, 2022 at 13:08
  • 1
    Got it ! changed the way I was storing item in local storage from localStorage.setItem('field-obj',this.fields) to localStorage.setItem('field-obj',JSON.stringify(this.fields)) and accessed it by this.fields = JSON.parse(localStorage.getItem('field-obj')) and it worked completely fine. Commented May 5, 2022 at 13:17

1 Answer 1

5

Setting it in the localStorage like this

localStorage.setItem('field-obj',JSON.stringify(this.fields))

and accessing it with this fixed the issue

this.fields = JSON.parse(localStorage.getItem('field-obj'))

A more complex example could be found here, using Nuxt.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.