Home > Mobile >  I use params and result :TypeError: Cannot read properties of undefined (reading 'map')
I use params and result :TypeError: Cannot read properties of undefined (reading 'map')

Time:12-19

export const listProducts = () => async (dispatch) => {
dispatch({ type: PRODUCT_LIST_REQUEST, 
});
try {
    const { data } = await Axios.get("/api/products");
    dispatch({type: PRODUCT_LIST_SUCCESS, payload: data });
    } catch (error) {
    dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message
    });
    }

};

  <div>
{loading ? (
  <LoadingBox></LoadingBox>
) : error ? (
  <MessageBox variant="danger">{error}</MessageBox>
) : (
  <div className="row center">
    {products.map(product => (
      <Product key={product._id} product={product} />
    ))}
  </div>
)}
);

When I try to run this code it gives me this error:

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

I don't know why. I have tried possible means, but it didn't work.

CodePudding user response:

Have you tried to log "products" to check it contains the data you are trying to map over after the fetch request?

The error message suggests products is undefined which is why the error shows since it can't map over an empty array.

If so, you could do a similar thing for loading and error where you conditionally render products. I've used the && (Logical AND) in the example below but there's a few ways to check products is not undefined (by length or use another ternary operator as in your example.

  <div>
{loading ? (
  <LoadingBox></LoadingBox>
) : error ? (
  <MessageBox variant="danger">{error}</MessageBox>
) : (
  <div className="row center">
    {products && products.map(product => (
      <Product key={product._id} product={product} />
    ))}
  </div>
)}

CodePudding user response:

Thank you for your answers thanks for your answers Fixed by updating productReducers.js

the error was:

return { loading: false, products: action.payload.products, };

deleted products keyword and fixed:

return { loading: false, products: action.payload, };

  • Related