Home > Mobile >  Changing form input data before POST request
Changing form input data before POST request

Time:12-03

I'm working with a reactjs frontend and springboot backend and I'm wondering how I can format/change form input data before I make a POST request to my backend. I'd like to maintain the dateFormat when displayed, but I'd like to change the value of the date to an ISO string before I make the POST request. New to react, so any discussion / help is appreciated.

import "./styles.css";
import DatePicker from 'react-datepicker';
import {useForm, Controller}  from "react-hook-form";
import "react-datepicker/dist/react-datepicker.css";

export default function App() {
  const {register, formState: { errors }, handleSubmit, control} = useForm();
  const onSubmit = (data) => {
    console.log(data.time.toISOString());
    fetch('/test', 
        {   method: 'POST',           
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
            },
            body: JSON.stringify(data),
        }
        );
  };

  return (
  <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
          name="time"
          control={control}
          render={({ field: { onChange, value} }) => (
              <DatePicker
                  onChange = {onChange}
                  selected= {value}
                  showTimeSelect
                  dateFormat="MMM d, yyyy h:mm aa"
              />
          )}
          rules={{ required:true}}
      />  
  <input type="submit"/>
  </form>
    );
}

CodePudding user response:

You're so close! Instead of just logging the transformed data, submit it as part of your post request:

const onSubmit = (data) => {
    const transformedTime = data.time.toISOString();
    // make a copy of data, but overwrite the time property with our transformed time
    const dataToSubmit = { ...data, time: transformedTime };
    // submit the new dataToSubmit object as a part of the request
    fetch('/test', 
        {   method: 'POST',           
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
            },
            body: JSON.stringify(dataToSubmit),
        }
        );
  };
  • Related