Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
Unable to access updated state inside handleEvent function | React Hooks

I am using DateRangePicker to get the date ranges and append the date to the api to get the latest dates data.

As in below code i can get updated state outside the EventHandler function but not inside it. I am getting the same date which is selected for the first time.

import React, { useState } from "react";
import DateRangePicker from "react-bootstrap-daterangepicker";
import "bootstrap-daterangepicker/daterangepicker.css";
import moment from "moment";
import DataProvider from "context/DataContext";

import ApiService from "services/api";

export default function DatePicker() {
  const [fromDate, setFromDate] = useState(new Date());
  const [toDate, setToDate] = useState(new Date());

  const range = {
    Today: [moment(), moment()],
    Yesterday: [moment().subtract(1, "days"), moment().subtract(1, "days")],
    "Last 7 Days": [moment().subtract(6, "days"), moment()],
    "Last 30 Days": [moment().subtract(29, "days"), moment()],
    "This Month": [moment().startOf("month"), moment().endOf("month")],
    "Last Month": [
      moment().subtract(1, "month").startOf("month"),
      moment().subtract(1, "month").endOf("month"),
    ],
    "Last Year": [
      moment().subtract(1, "year").startOf("year"),
      moment().subtract(1, "year").endOf("year"),
    ],
  };

  var startdate = moment(fromDate).format("yyyy-MM-DD");
  var enddate = moment(toDate).format("yyyy-MM-DD");

  console.log(startdate);

  const handleEvent = (event, picker) => {
  setFromDate(picker.startDate._d);
  setToDate(picker.endDate._d);
   
  console.log(startdate);

  var requestData = {
      metrics: ["views"],
      project_id: "abc",
      date_range: { start_at: fromDate, end_at: toDate },
    };

    ApiService.create({ requestData }).then((onSuccess) => {
      console.log(onSuccess);
    });
  };

  return (
    <DateRangePicker
      ranges={range}
      alwaysShowCalendars={false}
      onEvent={handleEvent}
    >
      <button>
        {moment(fromDate).format("ll")} to {moment(toDate).format("ll")}
      </button>
    </DateRangePicker>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In requestData object you should change fromDate to picker.startDate._d, same on the other one toDate->endDate._d

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda