Я получаю TypeError: не могу прочитать свойство '_id', равное undefined, когда я пытаюсь добавить элемент в корзину с помощью React. Я не уверен, что именно происходит, но думаю, что это связано с тем, как данные извлекаются из базы данных. Я использую MongoDB. Вот код:
import React, { useEffect, useState } from 'react'
import { Typography, Button, Form, message, Input, Icon } from 'antd';
import FileUpload from '../../utils/FileUpload'
import ProductInfo from '../DetailProductPage/Sections/ProductInfo'
import Axios from 'axios';
import { addToCart } from '../../../_actions/user_actions';
import { useDispatch } from 'react-redux';
const { Title } = Typography;
const { TextArea } = Input;
const Continents = [
{ key: 1, value: "Africa" },
{ key: 2, value: "Europe" },
{ key: 3, value: "Asia" },
{ key: 4, value: "North America" },
{ key: 5, value: "South America" },
{ key: 6, value: "Australia" },
{ key: 7, value: "Antarctica" }
]
function UploadProductPage(props) {
const [TitleValue, setTitleValue] = useState("")
const [DescriptionValue, setDescriptionValue] = useState("")
const [PriceValue, setPriceValue] = useState(0)
const [ContinentValue, setContinentValue] = useState(1)
const [Images, setImages] = useState([])
const onTitleChange = (event) => {
setTitleValue(event.currentTarget.value)
}
const onDescriptionChange = (event) => {
setDescriptionValue(event.currentTarget.value)
}
const onPriceChange = (event) => {
setPriceValue(event.currentTarget.value)
}
const onContinentsSelectChange = (event) => {
setContinentValue(event.currentTarget.value)
}
const updateImages = (newImages) => {
setImages(newImages)
}
const onSubmit = (event) => {
event.preventDefault();
if (!TitleValue || !DescriptionValue || !PriceValue ||
!ContinentValue || !Images) {
return alert('fill all the fields first!')
}
const variables = {
writer: props.user.userData._id,
title: TitleValue,
description: DescriptionValue,
price: PriceValue,
images: Images,
continents: ContinentValue,
}
Axios.post('/api/product/uploadProduct', variables)
.then(response => {
if (response.data.success) {
alert('Product Successfully Uploaded')
props.history.push('/')
} else {
alert('Failed to upload Product')
}
})
}
const dispatch = useDispatch();
const productId = props.match.params.productId
const [Product, setProduct] = useState([])
useEffect(() => {
Axios.get(`/api/product/products_by_id?id=${productId}&type=single`)
.then(response => {
setProduct(response.data[0])
})
}, [])
const addToCartHandler = (productId) => {
dispatch(addToCart(productId))
}
useEffect(() => {
setProduct(props.detail)
}, [props.detail])
const addToCarthandler = () => {
props.addToCart(props.detail._id)
}
return (
<div style={{ maxWidth: '700px', margin: '2rem auto' }}>
<div style={{ textAlign: 'center', marginBottom: '2rem' }}>
<Title level={2}> Upload Travel Product</Title>
</div>
<Form onSubmit={onSubmit} >
{/* DropZone */}
<FileUpload refreshFunction={updateImages} />
<br />
<br />
<label>Title</label>
<Input
onChange={onTitleChange}
value={TitleValue}
/>
<br />
<br />
<label>Description</label>
<TextArea
onChange={onDescriptionChange}
value={DescriptionValue}
/>
<br />
<br />
<label>Price($)</label>
<Input
onChange={onPriceChange}
value={PriceValue}
type="number"
/>
<br /><br />
<select onChange={onContinentsSelectChange} value={ContinentValue}>
{Continents.map(item => (
<option key={item.key} value={item.key}>{item.value} </option>
))}
</select>
<br />
<br />
<Button
onClick={function(event){onSubmit(event); addToCarthandler()}}
addToCart={addToCartHandler}
detail={productId}>
Submit
</Button>
</Form>
</div>
)
}
export default UploadProductPage
Получение этих ошибок в консоли:
xhr.js:155 GET http://localhost:3000/api/product/products_by_id?id=undefined&type=single 400 (Bad Request)
createError.js:17 Uncaught (in promise) Error: Request failed with status code 400
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:60)
Любая помощь была бы замечательной. Я не уверен, что именно делаю не так.