Warm tip: This article is reproduced from serverfault.com, please click

How to post request dates with react-date-range in React?

发布于 2020-11-30 15:30:19

I am relatively new to react and wanted to use the react-date-range library. For this, I want to send a POST request with axios the start date and the end date. However, I am having problems with combining the library and the post request. Can somebody help me with this problem? Because now the start dates and end dates are not submitted and I don't know what to do.

import React, { Component, useState } from 'react';
import './Datepickersearch.css';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; //theme css file
import { DateRangePicker } from 'react-date-range';
import { Button } from '@material-ui/core';
import { useHistory } from 'react-router-dom';
import axios from 'axios';

function Search() {
  const history = useHistory();
  const [startDate, setStartDate] = useState(new Date());
  const [endDate, setEndDate] = useState(new Date());

  const selectionRange = {
    startDate: startDate,
    endDate: endDate,
    key: 'selection',
  };

  function handleSelect(ranges) {
    setStartDate(ranges.selection.startDate);
    setEndDate(ranges.selection.endDate);
  }

  axios.post(`http://localhost:8080/api/reservation/`, { startDate, endDate }).then((res) => {
    console.log(res);
    console.log(res.data);
  });

  return (
    <div className="datepickersearch">
      <DateRangePicker ranges={[selectionRange]} onChange={handleSelect} />

      <h2> Number of guests</h2>
      <input min={0} defaultValue={2} max={7} type="number" />
      <Button onClick={() => history.push('/search')}>Search Apartments</Button>
    </div>
  );
}

export default Search;
Questioner
lara-div
Viewed
0
Madhuri 2020-12-01 02:02:14

You need to add onClick method on button, and call a method to post the data, dates are getting populated(check console statements).

Please check this code - https://codesandbox.io/s/axios-post-data-dhded?file=/src/Search.jsx