Home > database >  Cannot read properties of undefined (reading 'map') in react js with django backend
Cannot read properties of undefined (reading 'map') in react js with django backend

Time:08-04

I want to get my product's image of category 'Jeans' from django using DRF into my react frontend. Product Model looks like:(some fields are omited for simplicity)

class Product(models.Model):
    product_image = models.ImageField(upload_to='product_image', blank = True)

Serializer looks like:

class ProductSerializer(serializers.ModelSerializer):     
    class Meta: 
        model= Product 
        fields = ['product_image',]

View Looks like

class ProductView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self, request):
        Jeans = Product.objects.filter(category='Jeans')
        serializer = ProductSerializer(Jeans, many=True )
        return Response(serializer.data, status=status.HTTP_200_OK)

then using RTK API query, hooks are generated for GET Request and I get response (in Postman) like:

[
    {
        "product_image": "/media/product_image/jeans1_bsV3Jdg.jpg"
    },
    {
        "product_image": "/media/product_image/jeans2_76nciTn.jpg"
    },
    {
        "product_image": "/media/product_image/jeans3_SlMg4rG.jpg"
    }
]

But when I write code in React like this

import React, {useState, useEffect } from 'react'
import { useGetLoggedUserProfileDataQuery, useGetProductDataQuery } from './services/UserAuthApi'
import { getToken, removeToken } from './services/LocalStorageService'; 

const Product = () => {
    const {access_token} = getToken()
    const productimage = useGetProductDataQuery(access_token)
  return (
    <>
    {
        productimage.data.map((img)=>{
            <h1>{img.product_image}</h1>
        })
    }            
    </>  
  )
}

export default Product

I got the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

also on doing consolo.log(product_image), I got in console like this:

{status: 'fulfilled', endpointName: 'getProductData', requestId: 'oUVEcITKdMPJtGZ-Pod9P', originalArgs: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90e…I6MX0.9K9THmN--5WnBQX0i5n5XUXUb9bqqslRCqf7A2Smyj4', startedTimeStamp: 1659459361351, …}
currentData: (3) [{…}, {…}, {…}]
data: Array(3)
0: {product_image: '/media/product_image/jeans1_bsV3Jdg.jpg'}
1: {product_image: '/media/product_image/jeans2_76nciTn.jpg'}
2: {product_image: '/media/product_image/jeans3_SlMg4rG.jpg'}
length: 3
  [[Prototype]]: Array(0)

I just want to get product's image in react frontend using map method. Please Help me

CodePudding user response:

It's possible the http request hasn't completed before the DOM is trying to display the images, hence why it is saying the value is None type.

I get around this by using a ternary in the return that checks to see if there is a value in productimage. If there is, display it / map over it. If not, show something else (like a spinning wheel or some text like "..."

It would look something like this:

  const displayImg = (img) => {
   return(
   <h1>{img.product_image}</h1>
   )
  }

return (
    {productImage.data ? (
      productImage.data.map((img) => displayImg(img))
    ) : (
      <h1>loading...</h1>
    )}
)

  • Related