Search code examples
javascriptreactjsreact-context

React.JS Context API Problem (Rendering Problem)


I'm currently trying to implement a e-commerce project. My question is about Context API and Reducer. Cannot able to render price and other details of the product. in Cart Component

Context.Js ; Here is my Context.js

Reducer.JsHere is the Reducer.js

And My Product Component Code is ;

import './Product.css'
import AddBoxIcon from '@material-ui/icons/AddBox';
import { Context } from "./Context"
import React, {useContext} from "react"




function Product({title,price,image,id}) {

   const {addtoBasket} = useContext(Context)

/*
  function alertUser() {
        alert(`${title} added to your card`)
    }

    function addBasket(){
        console.log(title,price)
    }


    function firedFunctions(){
        alertUser()
        addBasket()
    
    }

*/
    
    return (
        <div className="product">
            <div className="product__info">
                <img src={image} alt=""></img>
                <p className="title">{title}</p>
                <div className ="price__add" >
                    <h4>Price : {price} $</h4>
                    <div onClick={() => addtoBasket(title, price, image,id)}>
                    <AddBoxIcon className="btn" />
                    </div>
                </div>                
            </div>            
        </div>
    )
}

export default Product

And My Cart Component Code is ;

import React, {useContext} from 'react'
import './Cart.css'
import {Context} from "./Context"
import Product from "./Product"


function Cart() {

    const {basket} = useContext(Context)
    console.log(basket) // Expected: Empty Array
    return (
        <div className="cart">
            <div className="cart__left">
                <h2>Your Products</h2>
                    <div>
                        {basket.map((product) =>(                          
                            <h4>{product}</h4>
                            {/*why product give me just a title of product*/}
                                                                     
                        ))}
                        
                    </div>

            </div>
            
            <div className="cart__right">
                <h2>Total</h2>
            </div>
        </div>
    )
}

export default Cart

And this is the output when i click the button v.1(console) ;

I want to see Price and image either.


Solution

  • You are passing three parameters to addToBasket function, however it is receiving just one object.

    Probably what you needs is:

    <div onClick={() => addtoBasket({title, price, image, id)}>
    

    I've just replicate it in codesandbox, this is the right answer, take a look: https://codesandbox.io/s/awesome-violet-fr7np?file=/src/index.js