Search code examples
javascriptlaravelvue.jslocal-storagelocal

Why local storage is changing every entry in task list


The local storage should only hold state for the task where the completed button has been pressed. Currently when I refresh the page all the tasks are marked as completed.

<template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
  {{ buttonText }}
</button>
</div>
</template>

<script>
export default {

props: 'itemId', required: true,
data() {
    return {
        index: 'this.itemId',
        status: ''
    }
},
methods: {
on_order_button_click() {
  this.status = !this.status;
  localStorage.setItem('index', this.status);
}

},
mounted() {

this.status = localStorage.getItem('index') === "true";
},
computed: {
buttonText() {
  return this.status === true ? "Completed" : "Complete";
},
 order_button_style() {
  return this.status === true
    ? "btn btn-danger"
    : "btn btn-primary";
}

}

};
</script>

Solution

  • In your calls to set localstorage, you are setting the item with a key of string 'index', not the index data property of your component. With what you have now, all components are reading from the same localstorage key.

    For example, change:

    mounted() {
        this.status = localStorage.getItem('index') === "true";
    },
    

    To:

    mounted() {
        this.status = localStorage.getItem(this.index) === "true";
    },
    

    Also, I don't think the way you are setting a data property equal to a passed property works. I've never seen that before. I think you are just setting your index data property equal to the string literal 'this.itemId'.

    I've rewritten your component trying to clean what errors I think there are. Let me know if this works.

    <template>
        <button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
            {{ buttonText }}
        </button>
    </template>
    
    <script>
    export default {
        props: {
            itemId: {
                type: String,
                required: true,
            }
        },
        data() {
            return {
                status: false,
            }
        },
        methods: {
            on_order_button_click() {
                this.status = !this.status;
                localStorage.setItem(this.itemId, this.status);
            }
        },
        mounted() {
            this.status = localStorage.getItem(this.itemId) === "true";
        },
        computed: {
            buttonText() {
                return this.status === true ? "Completed" : "Complete";
            },
            order_button_style() {
                return this.status === true ?
                    "btn btn-danger" :
                    "btn btn-primary";
            }
    
        }
    
    };
    </script>