Search code examples
arraysreactjsdatepickerfetch

React How to pass field date from datepicker as Api url parameter


I am fetching data from an API that has a date as a parameter
this date comes from the material picker of react the format for date should be yyyy-MM-dd, but when I select a date with my datepicker it passes date as

Tue Oct 12 2021 00:00:00 GMT+0000 (Greenwich Mean Time) I want the date sent by datpiecker to be as my required format: yyyy-MM-dd this is a prt of my code :

import React, { useState, useCallback, useEffect } from "react";
import DateFnsUtils from "@date-io/date-fns";
import {DatePicker, KeyboardDatePicker,MuiPickersUtilsProvider,} from "@material-ui/pickers";

function ExchangeRate() {
  

    const [date, setDate] = useState(moment().format("YYYY-MM-DD"));
   

    useEffect(() => {
   
  
    function getExchangeRates(base, currencyCode) {
       
        const url = `https://data.fixer.io/api/${date}?&base=USD`;

        
        return fetch(url)
            .then((res) => res.json())
            .then(handleAPIErrors)
            .then((res) => res.rates);
return (
          
          
                    </CSelect>
               
              


                  
          <MuiPickersUtilsProvider utils={DateFnsUtils}>
    
            <KeyboardDatePicker
            autoOk
              label="Material Date Picker"
              format="yyyy-MM-dd"
              animateYearScrolling
              value={date}
              onChange={date => setDate(date)}
            />
            
          </MuiPickersUtilsProvider>

Solution

  • You can format your date using moment when using the in the api URL as follow:

    const url = `https://data.fixer.io/api/${moment(date).format("YYYY-MM-DD")}?&base=USD`;
    

    Or if you want to consistently store the date with that format in the state, you can change the onChange event as follow:

    onChange={date => setDate(moment(date).format("YYYY-MM-DD"))}
    

    In the KeyboardDatePicker component the format prop only defines how the date is displayed in that component, and not how it is used in the onChange event.