skip to Main Content

I am having an issue in defaultValues. I am getting data from GET API and want to show the default values in the field which i got from the backend.
All the values are present in initialFieldValuesCopy but i’m unable to show them in my text fields. if a user want to change data it should be changeable means user will be able to make alteration in the data which is from the backend
i’m using PUT API like if the user changes the data in field it works and data is stored at backend

The code is given below

    interface UserData {
  id: string;
  email: string;
  fullName: string;
  phone: string;
  website: string;
  company: string;
  country: string;
  language: string;
  timeZone: string;
  currency: string;
  description: string;
  photoURL: string;
  // Add other fields with their types here
}

const AvatarViewWrapper = styled('div')(({ theme }) => {
  return {
    position: 'relative',
    cursor: 'pointer',
    '& .edit-icon': {
      position: 'absolute',
      bottom: 0,
      right: 0,
      zIndex: 1,
      border: `solid 2px ${theme.palette.background.paper}`,
      backgroundColor: alpha(theme.palette.primary.main, 0.7),
      color: theme.palette.primary.contrastText,
      borderRadius: '50%',
      width: 26,
      height: 26,
      display: 'none',
      alignItems: 'center',
      justifyContent: 'center',
      transition: 'all 0.4s ease',
      cursor: 'pointer',
      '& .MuiSvgIcon-root': {
        fontSize: 16,
      },
    },
    '&.dropzone': {
      outline: 0,
      '&:hover .edit-icon, &:focus .edit-icon': {
        display: 'flex',
      },
    },
  };
});

const PersonalInfo = () => {
  const { user } = useAuthUser();
  const { getRootProps, getInputProps } = useDropzone({
    accept: {
      'image/png': ['.png', '.jpg', '.jpeg'],
    },
    onDrop: (acceptedFiles) => {
      setImageFile(acceptedFiles[0]);
    },
  });

  const [imageFile, setImageFile] = useState<File | null>(null);
  const [initialFieldValues, setInitialFieldValues] = useState<UserData>({
    id: '',
    email: '',
    fullName: '',
    phone: '',
    website: '',
    company: '',
    country: '',
    language: '',
    timeZone: '',
    currency: '',
    description: '',
    photoURL: '/assets/images/placeholder.jpg',
  });

  useEffect(() => {
    // Fetch user details from the GET service
    const fetchUserData = async () => {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get(
          'https://admin.accountsdash.com/api/User/account',
          {
            headers: {
              accept: '*/*',
              'Content-Type': 'application/json',
              Authorization: `Bearer ${token}`,
            },
          }
        );

        const userResponse = response.data;
        console.log(userResponse);

        // Verify that userResponse is not empty and contains the expected data
        if (userResponse) {
          // Set the initial field values with the data from the API
          setInitialFieldValues({
            id: userResponse.id,
            email: userResponse.email,
            fullName: userResponse.fullName,
            phone: userResponse.phoneNumber,
            website: userResponse.webSite,
            company: userResponse.company,
            country: userResponse.country,
            language: userResponse.language,
            timeZone: userResponse.timeZone,
            currency: userResponse.currency,
            description: userResponse.description,
            photoURL: userResponse.photoURL || '/assets/images/placeholder.jpg',
          });
        } else {
          console.error('Received empty or unexpected data from the API.');
        }
      } catch (error) {
        console.error('Error fetching user data:', error);
      }
    };

    fetchUserData();
  }, []);

  const initialFieldValuesCopy = { ...initialFieldValues };
  console.log('Initial Field Values:', initialFieldValues);

  return (
    <Box
      sx={{
        position: 'relative',
        maxWidth: 550,
      }}
    >
      <Formik
        initialValues={initialFieldValues}
        validateOnChange={false}
        validateOnBlur={true}
        onSubmit={(values, { setSubmitting }) => {
          handleFormSubmit(values, imageFile, setSubmitting);
        }}
      >
        {({ values, setFieldValue, isSubmitting }) => (
          <Form>
            <AvatarBox>
              <AvatarViewWrapper {...getRootProps({ className: 'dropzone' })}>
                <input {...getInputProps()} />
                <label htmlFor="icon-button-file">
                  <AvatarStyle
                    src={initialFieldValues.photoURL || values.photoURL}
                  />
                  <Box className="edit-icon">
                    <EditIcon />
                  </Box>
                </label>
              </AvatarViewWrapper>
              <FullNameBox>
                <Typography
                  sx={{
                    fontWeight: Fonts.MEDIUM,
                  }}
                >
                  {initialFieldValues.fullName}
                </Typography>
                <Typography
                  sx={{
                    color: (theme) => theme.palette.text.secondary,
                  }}
                >
                  {initialFieldValues.email}
                </Typography>
              </FullNameBox>
            </AvatarBox>
            <Grid container spacing={2} sx={{ mb: 4 }} alignItems={'center'}>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  name="fullName"
                  label="Full Name"
                  defaultValue={initialFieldValues.fullName}
                  onChange={(e) => setFieldValue('fullName', e.target.value)}
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  name="email"
                  label="Email"
                  defaultValue={initialFieldValuesCopy.email}
                  disabled
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  name="phone"
                  label="Phone"
                  defaultValue={initialFieldValues.phone}
                  onChange={(e) => setFieldValue('phone', e.target.value)}
                />
              </Grid>
              {*/ Remaining Field */}
              <Button type="submit" name="submitButton">
              Submit
              </Button>
            </Form>
           )}
         </Formik>
        </Box>
       );
      };

The PUT API:

const handleFormSubmit = (
  data: UserData,
  imageFile: File | null,
  setSubmitting: (isSubmitting: boolean) => void
) => {
  setSubmitting(true);

  const formData = new FormData();
  if (imageFile) {
    formData.append('ProfileImage', imageFile);
  }
  formData.append('Id', '5eb37003-6923-4939-5241-08dbd3b53cb0');
  // eslint-disable-next-line no-debugger
  debugger;
  formData.append('Username', '[email protected]');
  formData.append('Email', '[email protected]');
  formData.append('PhoneNumber', data.phone);
  // formData.append('BirthDay', data.dob.toISOString());
  formData.append('BirthDay', '2023-10-02T19:00:00');
  formData.append('Website', data.website);
  // formData.append('Company', data.company);
  // formData.append('Country', data.country);
  formData.append('FullName', data.fullName);
  formData.append('Language', data.language);
  formData.append('TimeZone', data.timeZone);
  formData.append('Currency', data.currency);
  // formData.append('Description', data.description);

  // Append other form fields to formData
  // eslint-disable-next-line no-debugger
  debugger;

  const token = localStorage.getItem('token');
  axios
    .put('https://admin.accountsdash.com/api/User/account', formData, {
      headers: {
        accept: '*/*',
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${token}`,
      },
    })
    .then((response) => {
      console.log('User data updated:', response.data);
    })
    .catch((error) => {
      if (error.response) {
        console.error('Error updating user data:', error.response.data);
      } else {
        console.error('Network error:', error.message);
      }
    })
    .finally(() => {
      setSubmitting(false);
    });
};

Any Help will be Appreciated.
Thankyou

2

Answers


  1. The initialValues are only set during the first render in which no data is present yet.

    instead of setting the values in your useEffect with setInitialFieldValues you can try and use the resetForm with the values gained from the API according to the documentation

    Login or Signup to reply.
  2. As per your use case, you need to reinitialize the initial values of the form. There is a prop called enableReinitialize which defaults to false, set it to true to fix your issue. Here is the documentation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search