0

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Houssam, your solution works perfectly for the onChange i want the API to be fetched everytime i change the date, as useCallback, how to do that ?
You can achieve this by wrapping the code you want to execute when the date state variable change in a useEffect hook and passing as a second parameter (the dependency array) the following: [date]. This would result in useEffect(() => { ... }, [date]);. As a result, the effect will be executed on each change of that variable.
You can refer to the documentation about this: reactjs.org/docs/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.