So, I'm trying to use reduxtoolkit and want to create addtocart function and when try to set the payload I can't access the object property of my data.
const {data:foods,isPending,error} = useFetch('http://localhost:8000/foods')
const [data, setData] = useState(foods)
useEffect(()=>{
setData(foods)
},[foods]) console.log(data)
console.log(data.name)
const dispatch = useDispatch();
const addToCart = () => {
dispatch(
cartActions.addToCart({
name :data.name,
id:data.id,
price:data.price,
})
)
}
The Error: when I'm trying to log the object property it's returning undefined but when I log the data it showing up
CodePudding user response:
the reason I think you reciebe an array, you need add a index for get access:
dispatch(
cartActions.addToCart({
name :data[1].name,
id: data[1].id,
price: data.[1]price,
})
)
CodePudding user response:
You can clearly see that what you recieve from your API call is an array
, which has no name
property. However, items in this array have name
property (data[0].name
). What you need to do is to pass index
of an item you want to add to your cart into addToCart
function and based on that, access the right data[index]
item variable
const addToCart = (itemIndex) => {
dispatch(
cartActions.addToCart({
name :data[itemIndex].name,
id:data[itemIndex].id,
price:data[itemIndex].price,
})
)
}