Home > Back-end >  How to store an array in localStorage?
How to store an array in localStorage?

Time:04-20

I have a data property

 data() {
    return {
        playWord: [],
        baseWord: "",
        result: [],

    }
},

And response

   baseWord:"Amazing"

baseword changed each time I send new request in api. I want to store each data in local storage and send string value to axios post method.

My post method is here,

 methods: {
    name() {
        var name = localStorage.getItem("userName");
        console.log(name);
    },

    async playInfo() {
        this.$axios.post('user_play_info ', {
                words: "test",
                score: "5",
                user_name: localStorage.getItem('userName'),

            })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    }
},

i have been trying localstorage.setitem

 const testObject = this.baseWord
    console.log(testObject);

    localStorage.setItem('testObject', JSON.stringify(testObject));

    var retrievedObject = localStorage.getItem('testObject');

    console.log(retrievedObject);

how can I store my data in array? and send sting value through api response.

CodePudding user response:

Here is a complete example on how to work with an API use localStorage properly in Nuxt

<template>
  <div>
    <button @click="cleanPlaylist">Clean the playlist</button>

    <p>Items</p>
    <ul v-for="user in users" :key="user.id">
      <li>
        <span>{{ user.name }}</span> ~
        <span>{{ user.email }}</span>
        <button @click="saveToLocalStorage(user)">Save this user</button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [],
    }
  },
  async fetch() {
    const response = await fetch('https://jsonplaceholder.typicode.com/users')
    const json = await response.json()
    console.log('json', json)
    this.users = json
  },
  methods: {
    saveToLocalStorage(user) {
      if (localStorage.getItem('playlist')?.length) {
        const currentUsers = JSON.parse(localStorage.getItem('playlist'))
        console.log('current users', currentUsers)
        const newData = [...currentUsers, user]
        localStorage.setItem('playlist', JSON.stringify(newData))
      } else {
        localStorage.setItem('playlist', JSON.stringify([user]))
      }
    },
    cleanPlaylist() {
      localStorage.removeItem('playlist')
    },
  },
}
</script>

A codesandbox can be found here.

You should have a good amount of example code there are some console.log to understand what is happening. Of course, the browser devtools (Application tab) are recommended.

  • Related