-2

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

[1]: https://i.stack.imgur.com/OGzrO.png

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 2
    Your data didn't load yet, that's why – Konrad Aug 23 '22 at 18:58
  • 1
    You are also getting `undefined` from `console.log` in line 47, but you ignored it – Konrad Aug 23 '22 at 19:00
  • 1
    [Please do not upload images of code/data/errors when asking a question.](//meta.stackoverflow.com/q/285551) – Heretic Monkey Aug 23 '22 at 19:01
  • Use `console.log(JSON.stringify(data, null, 2))` to log the value of `data` at the time `console.log` is called instead of the lazy loading browsers use. – Heretic Monkey Aug 23 '22 at 19:02
  • `data` is an array - it doesn't have a `name` property. – VLAZ Aug 23 '22 at 19:03
  • Does this answer your question? [Can't access object property, even though it shows up in a console log](https://stackoverflow.com/questions/17546953/cant-access-object-property-even-though-it-shows-up-in-a-console-log) – Heretic Monkey Aug 23 '22 at 19:03

2 Answers2

2

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,
        })
    )
CoolLife
  • 1,419
  • 4
  • 17
  • 43
1

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,
        })
    )
} 
deaponn
  • 837
  • 2
  • 12