Format date to "YYYY-MM-DD" before post data to an API , Redux-Saga

Viewed 507

I use Formik module for handling form and DateInput of "react-hichestan-datetimepicker" module in my project. Output of DateInput is "2019-10-25T20:30:00.000Z". I want to send date value as this format "2019-10-25" to API. I change the format in onSubmit attribute of Formik.

<Formik
  initialValues={{
    date: ""
  }}
  onSubmit={(values, action) => {
    const data = { 
      ...values, 
      date: values.date.split("T")[0]
    };
    dispatch(
      createWorkingShift({ data, history: props.history })
    );
  }}
//...

here is saga:

const { data, history } = action.payload;
  try {
    const createWorkingShift = yield call(async () => {
      const workingShift = await httpService.post(
        "http://api.../v1/manager/ws/create",
        data
      );
      if (workingShift.status !== 200) {
        throw new Error("failed");
      }
      return {
        data: workingShift.data.working_shift,
        message: "success"
      };
    }); 
    yield put({ type: CREATE_WORKING_SHIFT_SUCCESS, payload: createWorkingShift });
    //...

with action:

export const createWorkingShift = payload => {
  return {
    type: CREATE_WORKING_SHIFT_REQUESTED,
    payload
  };
};

Date format change correctly in data variable in onSubmit, but data not sent to API.

When i delete date: values.date.split("T")[0] data delivery is successful!

I don't know what and where is the problem?

Thanks for your help.

1 Answers

I recommend you to use MomentJS

const formatedDateString = moment(yourdate).format('YYYY-MM-DD').toString();
Related