seven
seven

Reputation: 185

React-Redux UI bug. Lag in Image update

I'm building the MERN eCommerce app, and I'm facing a weird UI bug with pulling data from Redux Store. After switching pages from one product page to another, there is the old product image shown and then updated. As you can see: https://i.sstatic.net/PI1QO.jpg

There you can see code for reducer:

export const productDetailsReducer = (
  state = { product: { reviews: [] } },
  action
) => {
  switch (action.type) {
    case PRODUCT_DETAILS_REQUEST:
      return { loading: true, ...state };
    case PRODUCT_DETAILS_SUCCESS:
      return { loading: false, product: action.payload };
    case PRODUCT_DETAILS_FAIL:
      return { loading: false, error: action.payload };
    default:
      return state;
  }
};

And also code for action:

export const listProductDetails = (id) => async (dispatch) => {
  try {
    dispatch({ type: PRODUCT_DETAILS_REQUEST });

    const { data } = await axios.get(`/api/products/${id}`);

    dispatch({
      type: PRODUCT_DETAILS_SUCCESS,
      payload: data,
    });
  } catch (error) {
    dispatch({
      type: PRODUCT_DETAILS_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

And lastly, there is component's code where I bringing redux store into the page

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

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

  useEffect(() => {
    dispatch(listProductDetails(match.params.id));
  }, [dispatch, match]);

  console.log(product);

  return (
    <>
      {loading ? (
        <Loader />
      ) : error ? (
        <Message variant="danger">{error}</Message>
      ) : (
        <Row>
          <Col md={8}>
            <Image src={product.image} alt={product.name} fluid />
          </Col>
...rest of component's code....

I know probably would be the best to not even use redux for a single product, but I'm using this project for practice, and I'm kinda stuck at this one.

Thanks to everyone!

Upvotes: 0

Views: 157

Answers (1)

tanmay
tanmay

Reputation: 7911

What you need to do is clear the selected product when you leave the detail page. You can do that using the return function of useEffect. So probably something like:

useEffect(() => {
  dispatch(listProductDetails(match.params.id));
  
  return () => {
    dispatch(clearSelectedProduct());        
  }
}, [dispatch, match]);

And add corresponding action and reducer changes..

case CLEAR_SELECTED_PRODUCT:
  return { loading: false, product: { reviews: [] } }; 

This way, when you arrive on the product detail page, the previous product is always cleared.

Upvotes: 1

Related Questions