1

How to get the dispatch to recognize each product when the button is clicked?

When the HTML is mapped through the examples array, there is an index given. But when I click the button to addToCart, the elements of objects of array, it shows undefined

{type: "ADD_TO_CART", item: {…}}
item: {id: undefined, name: undefined, price: undefined, desc: undefined, type: undefined, …}
type: "ADD_TO_CART"

This is Menu.js

import React, { useState } from 'react';
import examples from './examples';
import './Menu.css';
import { useStateValue } from './StateProvider';

const Menu = ({ id, name, imgUrl, desc, price, type }) => {
    const [dishes, setDishes] = useState(examples);
const [, dispatch] = useStateValue();

const addToCart = () => {
    // add item to basket
    dispatch({
        type: 'ADD_TO_CART',
        item: {
            id,
            name,
            price,
            desc,
            type,
            imgUrl,
        },
    });
};

return (
    <div className='menu'>
        <h1>Menu</h1>
        <div className='menu__starters'>
            <h1>Starters</h1>
            {dishes.map((dish, index) => (
                <div className='menu__column'>
                    <div className='menu__row'>
                        <div className='menu__card' key={index}>
                            <div className='menu__img'>
                                <img src={dish.imgUrl} alt='img' />
                            </div>
                            <div className='menu__desc'>
                                <div className='menu__name'>
                                    <h2>{dish.name}</h2>
                                </div>
                                <div className='menu__description'>
                                    <p>{dish.desc}</p>
                                </div>
                                <div className='menu__credentials'>
                                    <div className='menu__price'>
                                        <h5>Damage- ${dish.price}</h5>
                                    </div>
                                    <div className='menu__button'>
                                        <button onClick={addToCart} key={index}>
                                            Add to Cart ->
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            ))}
        </div>`

An array of objects is in another file examples.js which is exported. This is reducer.js

export const initialState = {
cart: [],
};

function reducer(state, action) {
    console.log(action);
    switch (action.type) {
        case 'ADD_TO_CART':
            // logic for adding item to cart
            return { state };
            break;
        case 'REMOVE_FROM_CART':
            //logic for removing item from cart
            return { state };
            break;
        default:
            return state;
    }
}

export default reducer;`

Blockquote

  • The problem here is unclear, is the dishes array empty? By the way you don't need `break` in switch/case if you `return` – Sinan Yaman Dec 26 '20 at 08:35
  • Yeah, I got that later about break and return. The problem was that when items were dispatched, addToCart function was not able to recognize them cause they were not defined in its scope. – krishna-chavan Dec 27 '20 at 06:46

1 Answers1

2

It's undefined because those variables are not defined in addToCart scope, you haven't passed any data to it.

You have to pass the dish into addToCart

<button onClick={()=>addToCart(dish)} ...>

And

const addToCart = ({ id, name, imgUrl, desc, price, type }) => {...}
Adithya
  • 1,688
  • 1
  • 10
  • 18
  • Why couldn't we do – krishna-chavan Dec 27 '20 at 06:47
  • If you don't use arrow functions inside onClick, if you use parenthesis, it will autmoatically fire the function not waiting for the user to click. Take a look at this: https://stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react – Sinan Yaman Dec 27 '20 at 07:32
  • So if we console log inside the function, it should be printed in the console immediately after or during the page loads, right? – krishna-chavan Dec 27 '20 at 09:23