Search code examples
javascriptreactjsdatetimeonchange

Setting state of Date Picker onChange


I am trying to update my two states based on the currently selected date using html date picker. The two states; startdate and enddate, none of them is getting updated onChange. Based on those updated states, I need to fetch data using those states data as query paramters. It consoles only initial state dates.

Here is the code:

import React, { Component } from "react";
import axios from "axios";

export default class Main extends Component {
  constructor() {
    super();


    var date = new Date();


    var newdate =
      date.getFullYear() +
      "-" +
      ("0" + (date.getMonth() + 1)) +
      "-" + 
      ("0" + (date.getDate())) ;



    this.state = {
      startdate: newdate,
      enddate: newdate,
      clicked: false
    };
  }


  setStartDate = e => {
      this.setState({
        startdate: e.target.value
      })

      console.log(this.state.startdate, 'STARTDATE');
  }



  setEndDate = e => {
    //console.log(e.target.value)

    this.setState({
      enddate: e.target.value,
    });

    console.log(this.state.enddate, 'ENDDATE');
    axios.post('http://132.148.144.133:5000/api/v2/resources/sentiments', {
        sentiment_type: 'positive',
        startdate:this.state.startdate,
        enddate: this.state.enddate
    })
    .then( (result) => {

        console.log(result.data)
    })
    .catch(err => {
        console.log(err)
    })
  }


  render() {
    return (
      <div>
        <label>From</label>
        <input
          type="date"
          name="startdate"
          value={this.state.startdate}
          onChange={this.setStartDate}
        />

        <label>To</label>
        <input
          type="date"
          name="enddate"
          value={this.state.enddate}
          onChange={this.setEndDate}
        />
      </div>
    );
  }
}

I have got to fetch the data as soon as the second input box gets updated with the selected date from the picker.


Solution

  • Give it a try with this code:

    import React, { Component } from "react";
    import axios from "axios";
    
    export default class Main extends Component {
      constructor() {
        super();
        const date = new Date();
        const newDate =
          date.getFullYear() +
          "-" +
          ("0" + (date.getMonth() + 1)) +
          "-" +
          ("0" + date.getDate());
    
        this.state = {
          startDate: newDate,
          endDate: newDate
        };
      }
    
      handleDateChange = ({ target: { name, value } }) => {
        this.setState({
          [name]: value
        });
    
        if (name === "endDate") {
          const { endDate, startDate } = this.state;
          axios
            .post("http://132.148.144.133:5000/api/v2/resources/sentiments", {
              sentiment_type: "positive",
              startdate: startDate,
              enddate: endDate
            })
            .then(result => {
              console.log(result.data);
            })
            .catch(err => {
              console.log(err);
            });
        }
      };
    
      render() {
        const { endDate, startDate } = this.state;
        console.log(this.state);
        return (
          <>
            <label>From</label>
            <input
              type="date"
              name="startDate"
              value={startDate}
              onChange={this.handleDateChange}
            />
            <label>To</label>
            <input
              type="date"
              name="endDate"
              value={endDate}
              onChange={this.handleDateChange}
            />
          </>
        );
      }
    }
    

    It's cleaner with a generic method that manages your date changes. I also felt free to refactor it a bit. Let me know if it works the way you wanted it to.