Search code examples
javascriptreactjsreduxreact-reduxstore

redux fetchs store data with delay


I'm new to redux and I'm trying to implement redux for my first project. everything looks fine but when i console.log the data from redux store, it gives me two empty array at first and then in the next lines array isn't empty. this causes map function not to work on my ProductCart element.

console:

BikesPage.js:22 []length: 0[[Prototype]]: Array(0)
BikesPage.js:22 []length: 0[[Prototype]]: Array(0)
BikesPage.js:22 (3) [{…}, {…}, {…}]
BikesPage.js:22 (3) [{…}, {…}, {…}]0: {_id: '6351a9a95814ff5815e61187', title: 'MTB', price: '500', __v: 0}1: {_id: '6351aa75f685aa64faeaf27d', category: 'bike', title: 'MTB', price: '5080', __v: 0}2: {_id: '6351aa96f685aa64faeaf27f', category: 'bike5', title: 'MTB', price: '3980', __v: 0}length: 3[[Prototype]]: Array(0)
BikesPage.js:22 (3) [{…}, {…}, {…}]0: {_id: '6351a9a95814ff5815e61187', title: 'MTB', price: '500', __v: 0}1: {_id: '6351aa75f685aa64faeaf27d', category: 'bike', title: 'MTB', price: '5080', __v: 0}2: {_id: '6351aa96f685aa64faeaf27f', category: 'bike5', title: 'MTB', price: '3980', __v: 0}length: 3[[Prototype]]: Array(0)
BikesPage.js:22 (3) [{…}, {…}, {…}]
BikesPage.js:22 (3) [{…}, {…}, {…}]
BikesPage.js:22 (3) [{…}, {…}, {…}]
BikesPage.js:22 (3) [{…}, {…}, {…}]
BikesPage.js:22 (3) [{…}, {…}, {…}]

reducer:

const initialState = {
  products: [],
};

export const productReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCH_ALL:
      return { ...state, products: [...action.payload] };
    case CREATE:
      return [state.products, action.payload];
    case UPDATE:
      return state.products.map((product) =>
        product._id === action.payload._id ? action.payload : product
      );
    case DELETE:
      return state.products.filter((product) => product._id !== action.payload);

    default:
      return state;
  }
};

combine reducers :

export const reducers = combineReducers({ products: productReducer });

action:


export const getProducts = () => async (dispatch) => {
  try {
    const { data } = await api.fetchProducts();
    dispatch({ type: FETCH_ALL, payload: data });
  } catch (error) {
    console.log(error.message);
  }
};

bike page component :

function BikesPage() {
  const dispatch = useDispatch();

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

  const product = useSelector((state) => state.products);
  const { products } = product;

  console.log(products);

  return (
    <Container>
      <Row>
        <Col>
          <div className="BikesPage">
            {(products.length > 0) &
              products.map((p) => {
                return <ProductCart price={p.price} title={p.title} />;
              })}
          </div>
        </Col>
      </Row>
    </Container>
  );
}

index.js file:

const store = createStore(reducers, compose(applyMiddleware(thunk)));

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

to solve this problem i'v even written the useEffect funvtion in app.js to dispatch getProducts() but it still doesn't work


Solution

  • You need to write double && not &

      {(products.length > 0) &&
                  products.map((p) => {
                    return <ProductCart price={p.price} title={p.title} />;
                  })}