here is my cartSlice.js code
import { createSlice } from "@reduxjs/toolkit";
const cartSlice = createSlice({
name: 'items',
initialState: {
items: []
},
reducers: {
addItem(state, action) {
console.log(state.items.filter(item => item.id === action.payload.id))
console.log(state.items.filter(item => item.id === action.payload.id) != [])
if (true) {
let item = action.payload[0]
let count = action.payload[1]
state.items.push({...item, count})
}
else {
console.log('asdas') //somelogic
}
},
removeItem(state, action) {
state.items = state.items.filter(item => item.id !== action.payload)
}
}
});
export const {addItem, removeItem} = cartSlice.actions;
export default cartSlice.reducer;
here is where i take action
import {React} from 'react'
import { addItem } from '/store/cartSlice'
import { useDispatch } from 'react-redux'
import { useState} from 'react'
export default function ProductPage() {
let { state } = useLocation()
let item = state.item
const [count, setCount ]= useState(1)
const dispatch = useDispatch()
const addTask = () => dispatch(addItem([item, count]))
return (
<>
<div className={classes.info}>
<h2 >{item.title}</h2>
<span className={classes.price}>{item.price}</span>
<div className={classes.quantity}>
<button onClick={() => setCount(count-1)}
className={classes.quantityButton}>-</button>
{count}
<button onClick={() => setCount(count+1)}
className={classes.quantityButton}>+</button>
</div>
<button className={classes.addToCartButton}
onClick={addTask}>Add to cart</button>
</div>
</>
)
}
here is console enter image description here
item is an object with keys title, id an some more
guys why does the second log in addItem returns true
first log returns an empty array in console
i have only started working with redux and dont understand how to work with state
so i wanted to check if the item from action is actually in state.items but it isnt working
Tima Savinov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.