antd autocomplete
interface IOption {
value: IProduct;
label: string | React.ReactNode;
}
const [productOptions, setProductOptions] = useState<IOption[]>([]);
const renderItem = (product: IProduct, title: string, imageUrl: string) => ({
value: product,
label: (
<Row key={product.id} style={{ display: "flex", alignItems: "center" }}>
<Avatar
shape="square"
size={64}
src={imageUrl}
style={{ minWidth: "64px" }}
/>
<Text style={{ marginLeft: "16px" }}>{title}</Text>
</Row>
),
});
const { refetch: refetchProducts } = useList<IProduct>({
resource: "products",
pagination: {
pageSize: 1000,
},
queryOptions: {
enabled: false,
onSuccess: (data) => {
const productOptions = data.data.map((item) =>
renderItem(item, ${item.name} / #${item.code}, item.image)
);
if (productOptions.length > 0) {
setProductOptions(productOptions);
}
},
},
});
useEffect(() => {
setProductOptions([]);
refetchProducts();
}, []);
<AutoComplete
options={productOptions}
filterOption={false}
onSelect={(value, option) => {
console.log(value);
console.log(option);
}}
<Input
size="large"
placeholder={t("search.placeholder")}
suffix={<SearchOutlined />}
/>
</AutoComplete>
help, why im i getting this error: Warning: Encountered two children with the same key, [object Object]. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
3 Replies
Hi @tuanna_. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
The error message you're seeing is related to React's list and key handling. When rendering a list of elements, each element should have a unique
key
prop. This helps React identify which items have changed, are added, or are removed, and it's crucial for the performance of dynamic children.
In your case, the error is likely coming from this part of your code:
The key
prop here should be unique for each product. If product.id
is not unique for each product, you will encounter this error. Make sure that product.id
is unique for each product.
If product.id
is indeed unique, the error might be coming from elsewhere in your code where you're rendering a list of elements. Check other parts of your code to ensure you're using unique keys when rendering lists.
For more information on lists and keys in React, you can check the React documentation (https://reactjs.org/docs/lists-and-keys.html).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@353701348463738885> kapa.ai is still learning and improving, please let us know how it did by reacting below
fair-rose•11mo ago
Hello @tuanna_ you need to debug your data and render methods
actually error is pretty clear. in react, children cannot have the same key