@Maria_Ink

Функция не видит переменные. Почему так происходит?

Функция onSubmit не видит переменные, хотя логи видят

const [newReservation, setNewReservation] = useState("");
	const userId = useSelector(selectUserId);
	const dispatch = useDispatch();
	const requestServer = useServerRequest();
	const userRole = useSelector(selectUserRole);
	const [arrivalDate, setArrivalDate] = useState();
	const [leavingDate, setLeavingDate] = useState();
	const [options, setOptions] = useState({});
	const [serverError, setServerError] = useState(null);

	const minDate = new Date().toISOString().substring(0, 10);

	const isGuest = userRole === ROLE.GUEST;
	const errorMessage = serverError;

	const onLDateChange = ({ target }) => setLeavingDate(target.value);
	const onArDateChange = ({ target }) => setArrivalDate(target.value);

	console.log(newReservation, "newR");
	console.log(arrivalDate, "Arr");
	console.log(userId, "user");
	console.log(roomId, "room");
	console.log(options, "number");

	const onSubmit = ({ userId, roomId, options, arrivalDate, leavingDate }) => {
		console.log("rc", userId, roomId, options, arrivalDate, leavingDate);
		dispatch(
			addReservationAsync(requestServer, {
				userId,
				roomId,
				options,
				arrivalDate,
				leavingDate,
			}),
		);
		setNewReservation("");
	};

	return (
		<div className={className}>
			{!isGuest && (
				<div className="new-reservation">
					<div>
						<div>
							<label>
								Дата заезда:
								<input
									type="date"
									name="date"
									min={minDate}
									value={arrivalDate}
									required
									onChange={onArDateChange}
								/>
							</label>
						</div>
						<div>
							<label>
								Дата отъезда:
								<input
									type="date"
									name="date"
									id="leavingDate"
									value={leavingDate}
									required
									onChange={onLDateChange}
								/>
							</label>
						</div>
					</div>

					<label htmlFor="breakfasts">Количество гостей:</label>
					<input
						type="number"
						name="number"
						id="amountOfPeople"
						value={options}
						onChange={({ target }) => {
							setOptions(target.value);
						}}
						required
					/>
					<button
						onClick={onSubmit}
					>
						Забронировать
					</button>
					{errorMessage && <AuthFormError>{errorMessage}</AuthFormError>}
				</div>
			)}
		</div>
	);
  • Вопрос задан
  • 130 просмотров
Решения вопроса 1
alexey-m-ukolov
@alexey-m-ukolov Куратор тега JavaScript
Вы указали аргумент функции и таким образом перезаписали переменные из скоупа выше. Нужно так:
const onSubmit = () => {
	console.log("rc", userId, roomId, options, arrivalDate, leavingDate);
	dispatch(
		addReservationAsync(requestServer, {
			userId,
			roomId,
			options,
			arrivalDate,
			leavingDate,
		}),
	);
	setNewReservation("");
};
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы