0

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 :)

1 Answer 1

2

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;
 }
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this, I would get an error: colors is undefined
You can pass the colors object like this, <ProductColor colors={product.colors || []} />. Or you can check if colors exists in the ProductColor component using an if block. I am updating the code so that it doesn't throw any error.
Well this || [] helps: <ProductColor colors={product.colors || []} />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.