Stinny
Stinny

Reputation: 199

Why do I keep getting undefined when accessing the data that came from API?

Using react redux in my project for state management. I have an 'isLoading' variable to render the html based on this, whether or not the data has arrived. It doesn't seem to do anything as I keep getting undefined and the pages doesn't load when trying to access product.images[0].url.

here is the component:

const ProductDetail = () => {
  const { productId } = useParams();
  const product = useSelector((state) => state.products.products);
  const isLoading = useSelector((state) => state.products.isLoading);
  const dispatch = useDispatch();

  useEffect(() => {
    getSingleProduct(productId, dispatch);
  }, []);

  const detailDisplay = () => {
    return (
      <div className='container flex'>
        <div className='container'>
          <img src={product && product?.images[0].url} /> //this is what is causing the error
        </div>
      </div>
    );
  };

  return (
    <>
      <Header />
      <div className='container mx-auto max-w-6xl mt-14'>
        {isLoading ? <Spinner /> : detailDisplay()}
      </div>
    </>
  );
};

export default ProductDetail;

here is the reducers/actions:

export const productSlice = createSlice({
  name: 'products',
  initialState: {
    products: [],
    isLoading: false,
    error: false,
  },
  reducers: {
    //get product/s
    getProductStart: (state) => {
      state.isLoading = true;
      state.error = false;
    },
    getProductSuccess: (state, action) => {
      state.isLoading = false;
      state.products = action.payload;
    },
    getProductFailure: (state) => {
      state.isLoading = false;
      state.error = true;
    },
  },
});

Upvotes: 0

Views: 50

Answers (1)

Anthony C
Anthony C

Reputation: 2157

In your initialState, you have isLoading: false, so it always calls detailDisplay in this condition {isLoading ? <Spinner /> : detailDisplay()}

And the state.products.products is [] because of the initial state products: [] so it will satisfy the first check but fails with undefined on the latter part of this <img src={product && product?.images[0].url} />

To get rid of the error, you can set the initial State to isLoading: true or modify

<img src={product && product.images && product.images.length && product?.images[0].url} /> `

Upvotes: 2

Related Questions