Duplicate keys detected 1 this may cause an update error

I keep getting an error when I add an item to the array which has duplicate id. i.e. active_widgets:Array[4] 0:Object id:1 name:"Text Blocks" selected:false set:false 1:Object ...

You need to bind to the key with a unique value. Not doing so will cause problems in your application when a change in data for a component with one key updates that component and the other component with the duplicate key.

You should assign a unique key property to each of the items in the active_widgets array and then bind the key to that property.


Without seeing any of your code, I don’t know what your unique use case is. But here are a couple ways you could add a unique key property to the items in your array.

Here’s an example doing that in the created method.

created() {
  this.active_widgets.forEach((item, index) => this.$set(item, 'key', index));
}

If you need to add a unique key when an item is added to this array, you could maintain a counter and increment it each time an addition is made:

let WidgetCount = 0;

export default {
  data() {
    return { active_widgets: [] }
  },
  methods: {
    addWidget(id, name) {
      this.active_widgets.push({ 
        id, 
        name, 
        selected: false,
        set: false, 
        key: WidgetCount++
      })
    }
  }
}

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@DmitryNeposidjaka

@eklundkristoffer

I’m currently experiencing this as well, did you manage to solve it yet?

@yyman001

我使用内嵌electron 调用也是一样会出现这个问题,web没发现这个问题

@yyman001

@yyman001

@hejianxian

@DmitryNeposidjaka @eklundkristoffer

In the newer version of vue, this error message does appear. I will find a way to fix this problem as soon as possible. Or you can lower the vue version first.

@Zanzavar

Same problem here. Unfortunately i cannot downgrade as i need to use Vue 2.5 in order to implement subscribing to actions.

@awulkan

@Zanzavar I think it was somewhere around 2.5.9 that this error log was introduced. So you can still be on 2.5.

Anyway, this error was probably always in VDDL, in the new Vue version they just decided to log it afaik.

@JuniorNunes7

I solved this problem defining a unique prefix to key:

<div v-for="(item, i) in items" :key="i"></div>

<div v-for="(item, i) in items2" :key="`A-${i}`"></div>

<div v-for="(item, i) in items3" :key="`B-${i}`"></div>
ChadTaljaardt, miaoyuxinbaby, armanist, h4rDkur, widem, SeregPie, realdennis, sirb0rab0g1, silencerspirit, akinhwan, and 66 more reacted with thumbs up emoji
kjhatis, DoGoodMore, breezefeng, edarioq, edwardz8, fpbrault, and SeonHyungJo reacted with thumbs down emoji
eeerrrttty, yoann9344, hababere, iWhite5, kavinluo, and Belicuss reacted with laugh emoji
meghjoshi, daLingZhong, haimich, edarioq, gromov-io, JuniorNunes7, 1422385892, marcotterra, conc2304, eeerrrttty, and 5 more reacted with hooray emoji
miaoyuxinbaby, akinhwan, daLingZhong, Tanyuta, hyzyla, mcisback, gongora92, edarioq, gromov-io, JuniorNunes7, and 12 more reacted with heart emoji
eeerrrttty, MajaIsakovic, hababere, kavinluo, nguyennmt3009, and Belicuss reacted with rocket emoji
eeerrrttty, kavinluo, HmZc, and Belicuss reacted with eyes emoji

@kjhatis

[Vue warn]: Duplicate keys detected: 'A-1'. This may cause an update error. 

After trying your solutiion it still says the same @JuniorNunes7

@hejianxian

@DoGoodMore

Even if the value of the key is changed, the only existing ID attribute will still be wrong

@Tanyuta

@mcisback

I solved this problem defining a unique prefix to key:

<div v-for="(item, i) in items" :key="i"></div>

<div v-for="(item, i) in items2" :key="`A-${i}`"></div>

<div v-for="(item, i) in items3" :key="`B-${i}`"></div>

thanks so much ! This solved my issue :D

@xiooLoo

I solved this problem defining a unique prefix to key:

<div v-for="(item, i) in items" :key="i"></div>

<div v-for="(item, i) in items2" :key="`A-${i}`"></div>

<div v-for="(item, i) in items3" :key="`B-${i}`"></div>

谢谢了, 很有效果, 只要保证Array的:key不一致就不会有问题了😁

kayawari

added a commit
to kayawari/martilda
that referenced
this issue

Jan 3, 2019

@kayawari

@abea
abea

mentioned this issue

Jan 24, 2019

@Lucascoml

@wenweih

@eeerrrttty

I solved this problem defining a unique prefix to key:

<div v-for="(item, i) in items" :key="i"></div>

<div v-for="(item, i) in items2" :key="`A-${i}`"></div>

<div v-for="(item, i) in items3" :key="`B-${i}`"></div>

Best answer, worked here!

@korsino

I solved this problem defining a unique prefix to key:

<div v-for="(item, i) in items" :key="i"></div>

<div v-for="(item, i) in items2" :key="`A-${i}`"></div>

<div v-for="(item, i) in items3" :key="`B-${i}`"></div>

Worked! Thank you 🙌

@marcelodmdo

In determinated case, we can have:
post list (5 per page)
when you create a new post, and append (or prepend) to reactive array, a new element is accounted for.
When you scroll after that, you will see that have duplicated object (retrieved from backend, 6 insted 5)
thats the error

@houtianqi-ansin

I solved this problem defining a unique prefix to key:

<div v-for="(item, i) in items" :key="i"></div>

<div v-for="(item, i) in items2" :key="`A-${i}`"></div>

<div v-for="(item, i) in items3" :key="`B-${i}`"></div>

Thank you, I solved it.

Duplicate keys detected: ‘X’. This may cause an update error. in VueJS datatable search

In my laravel vue application I have following datatable with some filters in a vue component(department-user-list.vue).

This list and the filters works fine but when I try to search a user by typing their names, it kept giving me following error,

Duplicate keys detected: ‘1025’. This may cause an update error.

—> at resources/js/components/reusable/datatable/Datatable.vue at resources/js/components/reusable/csCard.vue at resources/js/components/dashboard/communities/department/one-departments/department-user-list.vue

But when I try to filter the list by some other param, they get filtered without any error.

I’m struggling to find what I’m doing wrong here.

UPDATE

following is my non-filtered json data for a single user

Following is my controller function,

2 Answers 2

The sample data for single user has duplicate id values in certificate_matrix array (2nd and 11th record both have id of 443)

This would probably be causing an issue in the v-for loop at (where you do not have any :key actually)

Or at any other place where certificate_matrix records are being looped over

Using composite key combining value of two fields to generate unique key

One way to try to ensure unique keys on frontend is to have a combination (kind of like composite key index) as $-$ if that combination is to remain unique.

Using loop iteration index as composite suffix to generate unique key

If there is no other field value which can be combined to ensure unique keys for child nodes within v-for then the $-$ can be used to generate unique keys — eg:

Using uuid as unique key

Another way is to add a uuid column on the database tables and then use the uuid as key in the component markup including subcomponents where :key or :key-id are used.

Laravel makes it very easy to generate Uuid v4 — uuids via (string) Str::orderedUuid(); And also has $table->uuid(‘uid’)->index() column type for migration files.

Can even have uid stored when a new model record is being created/persisted

Update

Based on feedback via comment

Thank you for your answer, I have updated the question with the correct backend controller. The reason for id duplication is one user can have multiple departments. Because of that my eloquent gives me results with multiple user id’s for some results. When I tried to group the results by user.id, it gives me an 500 error, and I need to pass the user.id as the key rather than passing uuid since the id has used for other functions, like user deletion and all. Any way to group the result from the backend to get only unique user ids?

To ensure only unique user records being sent via response from the controller, filter out duplicate records for the $users collection via unique() method available on Collection

Источник

Vue.js common issue: Duplicate Keys stops components rendering.

The common issue in Vue.js

Intro

While working on Vue.js project, sometimes you might notice that component isn’t rendered, it only shows empty. The reasons could be many, for example, API data doesn’t return because of bad API request, or it does return but the structure is different from Spec, or even some Javascript logic conflicts in template.

So What happened?

As mentioned above, we had an component rendering issue, but the weird thing is it only happened on Prod, on local it still worked well , so this unusual behaviour made us suspect that some conflicts might happen on Prod server. Meanwhile, we also noticed some error message appears on console like below.

How we investigate this.

By checking the issue discussion on Vue.js github, someone mentioned replacing v-if with v-show in parent wrapper could solve the problem, and it worked for us, but this seemed to be hacky, doesn’t feel like a proper solution.

So we kept looking into this

“It turns out the keyed children inside v-for, will trigger this error while they have duplicate keys.”

In our case, each child component has link URL as their :key value, however, and error happened while two of the URL are identical.

How we fix it and how you can avoid it.

Simple as it is, just need to define a unique key for each child, you can use the index value of each item, or even adding prefix/suffix to it, as long as none of them won’t be identical, this shouldn’t cause this error anymore.

Question? 🤔

Ok, the issue is solved, but there are still something I wanna figure it out. Remember I mentioned while I replaced v-if with v-show then it worked, which made me want to deeply look into the difference between v-if and v-show .

According to Evan You’s explanation:

v-show always compiles and renders everything — it simply adds the “display: none” style to the element. It has a higher initial load cost, but toggling is very cheap.

In comparison, v-if is truely conditional: it is lazy, so if its initial condition is false, it won’t even do anything. This can be good for initial load time. When the condition is true, v-if will then compile and render its content. Toggling a v-if block actually teardown everything inside it, e.g. Components inside v-if are actually destroyed and re-created when toggled, so toggling a huge v-if block can be more expensive than v-show.

What I don’t understand is, as long as components are rendered, they should all show the error message, why this doesn’t happen in v-show , furthermore, the error message ONLY SHOWS in v-if condition.

So maybe it’s because…

In v-if , it has to monitor child components in order to re render anytime, then it notices the :key value is not set uniquely, which triggers error message. But this is just my guessing, will keep tracking this topic and very welcome if anyone knows the reason.

Meanwhile, why Dev mode works while Prod mode fails.

This actually made us go to the wrong direction to look into at beginning, we thought this might be some setting on server caused the issue, or maybe time zone issue, until we tried to run the Prod mode on local and realised it has nothing to do with server.

I reckon it’s because this is not a JS error, it’s a Vue conflict, and that’s why in Prod mode it isn’t aware of this kind of error, something went wrong beneath, which brought us some challenges for debugging.

Hi there, we are currently recruiting mentors on BrewCareer , if you have interest in coaching and guiding people to help them to approach next career goal, please feel free to sign up and join us 🙂

Источник

‘Duplicate keys detected: . ‘ error with same keyed children inside a v-fored template #7323

Comments

mathieumure commented Dec 26, 2017 •

Version

Reproduction link

Steps to reproduce

  • Open the jsfiddle demo
  • Open your console
  • Run the demo
  • now you should see an error like this: [Vue warn]: Duplicate keys detected:

What is expected?

Children inside a repeated should share the same keys as they should both re-render if the target element changes.

What is actually happening?

Errors are raised with the message : [Vue warn]: Duplicate keys detected is raised.

Cause

This behavior is linked to this PR and was also references in this issue

Workaround

You could avoid this error by adding some prefix / suffix

The text was updated successfully, but these errors were encountered:

posva commented Dec 26, 2017

Unfortunately, this is expected, both elements being at the same level (under ul ) you’re telling Vue they’re the same. As you said, you need to add a suffix or prefix to let Vue treat them differently
You may think it was working pre 2.5.10 because there was no warning but it was not always working, the warning was simply missing

mathieumure commented Dec 26, 2017

Thanks for the quick reply 👏

It makes perfectly sense (now that I know is not considered as an anonymous component by Vue) but I think a word on template and key in the doc could help others, especially when the doc said that «serves as an invisible wrapper.» 😄

posva commented Dec 26, 2017

Contributions to docs are always welcome but I think invisible wrapper is accurate and if you try to use key on template you also get an error, so, to me it looks we are covered but ofc open a PR on the docs if you found some case not covered 🙂

Источник

Русские Блоги

Duplicate keys detected: ‘0’. This may cause an update error.

Причина ошибки

В шаблоне два одинаковых v-for

Решения

Изменить его с помощью ключа

Интеллектуальная рекомендация

PostgressSQL-Installation

Установить Автоматически генерировать имя называетсяpostgres Пользователь системы Linux Измените пароль пользователя системы Postgres Используйте вход пользователя Postgres Перепечатано: https://www.c.

C # Читает файл Excel

Прочитайте файл Excel.

Ян Хуэй треугольник

Как вы говорите, никакое пространство печати не является треугольником Ян Хуэй, хахаха.

Python импортирует имя поисковой книги с allitebooks.com в базу данных.

Python импортирует имя поисковой книги с allitebooks.com в базу данных. Готов к работе 1. Программное обеспечение Python 2. Создайте базу данных. (Примечание. База данных и таблица данных могут быть с.

Visual Paradigm — простой в использовании инструмент UML

www.visual-paradigm.com Простой в использовании инструмент UMLилиБесплатный онлайн инструмент UML Диаграмма вариантов использования Захват функциональных требований с помощью диаграмм вариантов .

Вам также может понравиться

First Variation on Caesar Cipher

Оригинальное название: https://www.codewars.com/kata/5508249a98b3234f420000fb *The action of a Caesar cipher is to replace each plaintext letter with a different one a fixed number of places up or dow.

Аперео CAS

Прихоть хочет построить систему единой регистрации для компании. В конце концов, в интранете так много систем, и у каждой системы есть набор паролей учетных записей, который настолько низок. CAS предо.

3.python Common Challent.

содержание Выявление суждения 2. Круговое утверждение 3. Другое утверждение Addthon Выявление суждения 1.ifЗаявление Формат: Если условия суждения: Что делать, когда вы соответствуете условиям 1 . Ч.

Конфигурация компьютера Android-студия очень высока, это очень карта?

Новая погода Нового года, я изменил компанию позже, я могу сосредоточиться на развитии Android, я могу разрабатывать новые приложения, изучать новый язык, знакомый с новой средой, знаю новые коллега и.

LVS Cluster подробное объяснение

1. Что такое кластер LVS (Linux Virtual Server) Virtual Server Linux организует несколько виртуальных хостов для удовлетворения одинаковых потребностей. Разработанный китайским человеком Чжаном Венонг.

Источник

Vue.js common issue: Duplicate Keys stops components rendering.

The common issue in Vue.js

Intro

While working on Vue.js project, sometimes you might notice that component isn’t rendered, it only shows empty. The reasons could be many, for example, API data doesn’t return because of bad API request, or it does return but the structure is different from Spec, or even some Javascript logic conflicts in template.

So What happened?

As mentioned above, we had an component rendering issue, but the weird thing is it only happened on Prod, on local it still worked well , so this unusual behaviour made us suspect that some conflicts might happen on Prod server. Meanwhile, we also noticed some error message appears on console like below.

How we investigate this.

By checking the issue discussion on Vue.js github, someone mentioned replacing v-if with v-show in parent wrapper could solve the problem, and it worked for us, but this seemed to be hacky, doesn’t feel like a proper solution.

So we kept looking into this

“It turns out the keyed children inside v-for, will trigger this error while they have duplicate keys.”

In our case, each child component has link URL as their :key value, however, and error happened while two of the URL are identical.

How we fix it and how you can avoid it.

Simple as it is, just need to define a unique key for each child, you can use the index value of each item, or even adding prefix/suffix to it, as long as none of them won’t be identical, this shouldn’t cause this error anymore.

Question? 🤔

Ok, the issue is solved, but there are still something I wanna figure it out. Remember I mentioned while I replaced v-if with v-show then it worked, which made me want to deeply look into the difference between v-if and v-show .

According to Evan You’s explanation:

v-show always compiles and renders everything — it simply adds the “display: none” style to the element. It has a higher initial load cost, but toggling is very cheap.

In comparison, v-if is truely conditional: it is lazy, so if its initial condition is false, it won’t even do anything. This can be good for initial load time. When the condition is true, v-if will then compile and render its content. Toggling a v-if block actually teardown everything inside it, e.g. Components inside v-if are actually destroyed and re-created when toggled, so toggling a huge v-if block can be more expensive than v-show.

What I don’t understand is, as long as components are rendered, they should all show the error message, why this doesn’t happen in v-show , furthermore, the error message ONLY SHOWS in v-if condition.

So maybe it’s because…

In v-if , it has to monitor child components in order to re render anytime, then it notices the :key value is not set uniquely, which triggers error message. But this is just my guessing, will keep tracking this topic and very welcome if anyone knows the reason.

Meanwhile, why Dev mode works while Prod mode fails.

This actually made us go to the wrong direction to look into at beginning, we thought this might be some setting on server caused the issue, or maybe time zone issue, until we tried to run the Prod mode on local and realised it has nothing to do with server.

I reckon it’s because this is not a JS error, it’s a Vue conflict, and that’s why in Prod mode it isn’t aware of this kind of error, something went wrong beneath, which brought us some challenges for debugging.

Hi there, we are currently recruiting mentors on BrewCareer , if you have interest in coaching and guiding people to help them to approach next career goal, please feel free to sign up and join us 🙂

Источник

Содержание

  1. Vue.js common issue: Duplicate Keys stops components rendering.
  2. Intro
  3. So What happened?
  4. How we investigate this.
  5. How we fix it and how you can avoid it.
  6. Question? 🤔
  7. So maybe it’s because…
  8. Meanwhile, why Dev mode works while Prod mode fails.
  9. nested v-for by component and template bug #3810
  10. Comments
  11. Vue.js version
  12. Reproduction Link
  13. Steps to reproduce
  14. What is Expected?
  15. What is actually happening?
  16. Русские Блоги
  17. Duplicate keys detected: ‘0’. This may cause an update error.
  18. Причина ошибки
  19. Решения
  20. Интеллектуальная рекомендация
  21. Запрос по поводу, связанный с рассмотрением, объяснение глобальных ординалов и высокой кардинальности Elasticsearch
  22. Хакатон по инновациям Hangdian
  23. запрос гибернации
  24. a single class with a shared lookup-table that defines the shared info

Vue.js common issue: Duplicate Keys stops components rendering.

The common issue in Vue.js

Intro

While working on Vue.js project, sometimes you might notice that component isn’t rendered, it only shows empty. The reasons could be many, for example, API data doesn’t return because of bad API request, or it does return but the structure is different from Spec, or even some Javascript logic conflicts in template.

So What happened?

As mentioned above, we had an component rendering issue, but the weird thing is it only happened on Prod, on local it still worked well , so this unusual behaviour made us suspect that some conflicts might happen on Prod server. Meanwhile, we also noticed some error message appears on console like below.

How we investigate this.

By checking the issue discussion on Vue.js github, someone mentioned replacing v-if with v-show in parent wrapper could solve the problem, and it worked for us, but this seemed to be hacky, doesn’t feel like a proper solution.

So we kept looking into this

“It turns out the keyed children inside v-for, will trigger this error while they have duplicate keys.”

In our case, each child component has link URL as their :key value, however, and error happened while two of the URL are identical.

How we fix it and how you can avoid it.

Simple as it is, just need to define a unique key for each child, you can use the index value of each item, or even adding prefix/suffix to it, as long as none of them won’t be identical, this shouldn’t cause this error anymore.

Question? 🤔

Ok, the issue is solved, but there are still something I wanna figure it out. Remember I mentioned while I replaced v-if with v-show then it worked, which made me want to deeply look into the difference between v-if and v-show .

According to Evan You’s explanation:

v-show always compiles and renders everything — it simply adds the “display: none” style to the element. It has a higher initial load cost, but toggling is very cheap.

In comparison, v-if is truely conditional: it is lazy, so if its initial condition is false, it won’t even do anything. This can be good for initial load time. When the condition is true, v-if will then compile and render its content. Toggling a v-if block actually teardown everything inside it, e.g. Components inside v-if are actually destroyed and re-created when toggled, so toggling a huge v-if block can be more expensive than v-show.

What I don’t understand is, as long as components are rendered, they should all show the error message, why this doesn’t happen in v-show , furthermore, the error message ONLY SHOWS in v-if condition.

So maybe it’s because…

In v-if , it has to monitor child components in order to re render anytime, then it notices the :key value is not set uniquely, which triggers error message. But this is just my guessing, will keep tracking this topic and very welcome if anyone knows the reason.

Meanwhile, why Dev mode works while Prod mode fails.

This actually made us go to the wrong direction to look into at beginning, we thought this might be some setting on server caused the issue, or maybe time zone issue, until we tried to run the Prod mode on local and realised it has nothing to do with server.

I reckon it’s because this is not a JS error, it’s a Vue conflict, and that’s why in Prod mode it isn’t aware of this kind of error, something went wrong beneath, which brought us some challenges for debugging.

Hi there, we are currently recruiting mentors on BrewCareer , if you have interest in coaching and guiding people to help them to approach next career goal, please feel free to sign up and join us 🙂

Источник

nested v-for by component and template bug #3810

Vue.js version

Reproduction Link

Steps to reproduce

use a v-for to render component
in component, you have to write a v-for with template in it but not wrapped with a root element
open console, and run test() function

What is Expected?

open console, and run success() function
or you can click https://codepen.io/toxic-johann/pen/JRJgGJ?editors=1111.
when i keep on one root element in v-for, the problem dispear.

So I think, if vue consider multiple element int the template is forbidden.It should throw a warn.
Otherwise, it’s a bug

What is actually happening?

throw the warning

[Vue warn]: It seems there are duplicate keys that is causing an update error. Make sure each v-for item has a unique key.
and error
Uncaught (in promise) TypeError: Cannot read property ‘tag’ of undefined

it’s the same problem with #3807
u can reopen that.

The text was updated successfully, but these errors were encountered:

It actually works when v-if=»toy.name != ‘b’» is replaced with with v-else

It also works when the inner is replaced with

And it works when the outer is replaced with

So I guess it’s using multiple s inside a v-for ed that caused the problem, but I doubt if it’s the root cause, because I don’t think keying a should be valid..
If not, it should indeed be warned about.

Источник

Русские Блоги

Duplicate keys detected: ‘0’. This may cause an update error.

Причина ошибки

В шаблоне два одинаковых v-for

Решения

Изменить его с помощью ключа

Интеллектуальная рекомендация

Запрос по поводу, связанный с рассмотрением, объяснение глобальных ординалов и высокой кардинальности Elasticsearch

От:https://blog.csdn.net/zwgdft/article/details/83215977 【README】 Есть много концепций в Elasticsearch. Эта статья будет подробно описана из проблем, с которыми я столкнулся в процессе практики.

Хакатон по инновациям Hangdian

Хакатон инноваций 2015 Security Control Cup, который совместно организован Обществом компьютерных наук и технологий Школы компьютерных наук и технологий Университета Дяньцзы в Ханчжоу и сообществом He.

запрос гибернации

запрос гибернации запрос критериев: http://blog.csdn.net/xingtianyiyun/article/details/7703429 http://www.cnblogs.com/JemBai/archive/2010/01/06/1640636.html Hibernate получить и разница в нагрузке Кат.

a single class with a shared lookup-table that defines the shared info

100+ almost identical classes is crazy. Classes are organizational structures. Having dozens of them with almost no variation does’t seem useful. It’s over-specialization. It sounds very much like you.

Источник

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Duplicate declaration in current scope ошибка vba
  • Duplicate class ошибка java
  • Duolingo произошла ошибка
  • Duolingo как изменить язык интерфейса
  • Dungeon siege 2 нет курсора windows 10 как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии