besartm
besartm

Reputation: 568

Passing an array of object to another component is undefined - React & Redux

I have build an reactjs app with redux: I created store, reducer,action and everything is working fine. When I make request from action to backend, it would get an object. The object is something like this: example-Product:

{
   name: 'pro 1',
   category: 'category 2',
   colors: ['red', 'blue', 'green']
}

The view is looking something like this:

const ProductView = ({ match }) => {
    const dispatch = useDispatch();

    const productDetails = useSelector(state => state.productDetails )
    const { loading, error, product} = productDetails ;

    useEffect(()=>{
        dispatch(detailsProd(match.params.id))
    },[dispatch,  match]) 
return(
<>
   { loading ? (
                <Loader />
            ): error ?(
                <Message variant='danger'>{error}</Message>
            ):(
               <h1>{product.name}</h1>
               **<ProductColor colors={product.colors} />**
            )
   }
</>
)
}

Now when I pass colors array of object on the ProductColor Component, firstly is undefined than it takes the colors, but it is not showing on the Product Color Component.

const ProductColor = (colors) => {
    console.log('array: ',colors);

    return (
    <>
    {
        colors.map(c => (
            <p key={c}>{ c }</p>
        ))
    }
    </>
    )
}

Should I make any change on redux or here on this component? Thank you :)

Upvotes: 0

Views: 208

Answers (1)

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5054

You are passing the colors as props in the ProductColor component. You should write that component like this,

const ProductColor = ({colors}) => {
    if(colors) {
      console.log('array: ',colors);

       return (
          <>
               {
                colors.map(c => (
                   <p key={c}>{ c }</p>
                ))
             }
          </>
       )
    }

    return null;
 }

Upvotes: 2

Related Questions