[Vue warn]: Duplicate value found in v-for

Posted 1 year ago by TimeSocks

Hi folks,

I have a Vue (1.x) based shopping basket system working in conjunction with a Laravel backend using Moltin-Cart. The basket is populated, retrieved and updated using API calls to the backend.

I can add items to the basket without an issue:

addToBasket: function(){
                var that = this;
                var item = this.book;
                this.$http.post('/api/buy/addToBasket', item);
                this.basketAddSuccess = true;
                setTimeout(function(){ that.basketAddSuccess = false; }, 4000);

which hits the backend:

public function addToBasket(Request $request)
        // grab photo information
        $book = Book::find($request->id);

        // extract price from the database to ensure it's correct
        $row = $book->price;
        // create an item
        $item = array(
                'id' => $book->id,
                'name' => $book->title,
                'price' => $row,
                'quantity' => $request->qty

        // Make the insertion...

When I hit my fetchBasket API function I get this as expected:

027c91341fd5cf4d2579b49c4b6a90da: {
id: 1,
name: "Book Title",
price: 40,
quantity: "1"

The long random string is the cart id.

The problem comes when I try to list the basket contents using a simple v-for:

<tr v-for="item in basketItems">

But this throws lots of errors:

[Vue warn]: Duplicate value found in v-for="item in basketItems": "0". Use track-by="$index" if you are expecting duplicate values.

One error for each character in the JSON string, in fact.

So Googling around I find track-by and try to implement it first with item.id:

<tr v-for="item in basketItems" track-by="item.id">

This throws VM4389:3 Uncaught TypeError: Cannot read property 'id' of undefined

I have also tried:

<tr v-for="item in basketItems" track-by="id">

But this throws the 'one error for every character in the JSON string' thing at me.

Then I tried with $index:

<tr v-for="item in basketItems" track-by="$index">

This doesn't throw an error, but it instead creates an empty basket item entry in the basket view for each character in the JSON string.

Any ideas as to how to fix it?

Please sign in or create an account to participate in this conversation.