i already take few hourse to solve this, but still not done yet. can somebody help me to solve this pls.
import { createSlice, createAsyncThunk, current } from ‘@reduxjs/toolkit’;
import axios from ‘axios’;
export const addToCart = createAsyncThunk(
'cart/addCart',
async (obj, thunkAPI) => {
const response = await axios.get(
`http://localhost:8000/api/products/${obj.id}`
);
const data = await response.data;
thunkAPI.dispatch(
cartAdd({
product: data._id,
name: data.name,
image: data.image,
price: data.price,
countInStock: data.countInStock,
qty: obj.qty,
})
);
localStorage.setItem(
'cartItems',
JSON.stringify(thunkAPI.getState().cart.cartItems)
);
}
);
const cartItemsFromStorage = localStorage.getItem('cartItems')
? JSON.parse(localStorage.getItem('cartItems'))
: [];
const cartSlice = createSlice({
name: 'cart',
initialState: {
isLoading: false,
cartItems: cartItemsFromStorage,
},
reducers: {
cartAdd(state, { payload }) {
const existItem = JSON.parse(JSON.stringify(state.cartItems)).find(
(elem) => elem.product === payload.product
);
console.log(existItem);
if (existItem) {
return {
...state,
cartItems: state.cartItems.map((x) =>
x.product === payload.product ? payload : x
),
};
} else {
return {
...state,
cartItems: [...state.cartItems, payload],
};
}
},
},
extraReducers: {
[addToCart.pending]: (state, { payload }) => {
state.isLoading = true;
},
[addToCart.fulfilled]: (state, action) => {
state.isLoading = false;
state.cartItems = action.payload;
},
[addToCart.rejected]: (state, action) => {
console.log(action);
state.isLoading = false;
},
},
});
the existing item give the result
{product: '628f92cfab7a84a5ab78fa3a', name: 'Airpods Wireless Bluetooth Headphones', image: '/images/airpods.jpg', price: 89.99, countInStock: 10, …}
countInStock: 10
image: "/images/airpods.jpg"
name: "Airpods Wireless Bluetooth Headphones"
price: 89.99
product: "628f92cfab7a84a5ab78fa3a"
qty: 1
[[Prototype]]: Object
but rejected condition always give this
"SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at cartAdd (http://localhost:3000/static/js/bundle.js:932:30)
at http://localhost:3000/static/js/bundle.js:3172:20
at produce (http://localhost:3000/static/js/bundle.js:69721:15)
at http://localhost:3000/static/js/bundle.js:3171:67
at Array.reduce (<anonymous>)
at reducer (http://localhost:3000/static/js/bundle.js:3147:25)
at reducer (http://localhost:3000/static/js/bundle.js:3241:14)
at combination (http://localhost:3000/static/js/bundle.js:63408:29)
at k (<anonymous>:2235:16)"
can somebody help to get through this? thank you very much