reactjsreact-reduxkeydispatch

Why I am getting "Each child in a list should have a unique "key" prop" even though my code has a key?


I have an API endpoint to get all the products. It is working well. Now I am trying to fetch and display the data in frontend using redux (even though there is redux-toolkit, I am doing this for learning purpose). I can view the fetched data using redux-dev-tool. But it is not displayed on the page. Though I provide a unique key, I am getting, Each child in a list should have a unique "key" prop - in my console.

Here is my Home component


const Home = ()=>{
    const dispatch = useDispatch()
    const { loading, error, products } = useSelector((state) => state.products);
//I can view the data here when I use console.log
    useEffect(() => {
      dispatch(getProduct())
    }, [dispatch])
    return(
<Fragment>
    <h2 className='homeHeading'>Featured Products</h2>
    <div className='container' id='container'>
    {products &&
              products.map((product) => (
                 <h1 key={product._id}>{product.name}</h1>
              ))}
    </div>
</Fragment>
    )
}
export default Home

Solution

  • try to debug with following factors.

    1. check whether error if error is throwing for products.map or there any other map as well.

    2. if its for product array only then most probably you are getting duplicate id in the array. Id should be alway unique but you can add suffix to key.

    3. as you are fetching data from api, add null checks

      {products && products?.map((product, index) => <h1 key={product?._id + index}>{product?.name})}