Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
getting null values in formData in react hooks

Hello all I am facing some issues while using react functional components hooks with formData i am getting null data in formData i am using usestate hooks but i am getting balnk array as output

const [profilestate, setProfileState] = useState({
        dob:"",
        city:"",
        state:"",
        country:"",
        school: "",
        board: "",
        age: "",
        gender: "",
        degree_college: "",
        masters_college: "",
        organizations: "",
        department: "",
        title: "",
        profile_image:""
});

const handleChange = (e) => {
        setProfileState({
            ...profilestate,
            [e.target.name]: e.target.value
      });
}
const handleFileChange = (e) => {
        setProfileState({
            ...profilestate,
            profile_image: e.target.files[0]
        })
}
    
const { dob, state, city, country, school, board, age, gender, degree_college, masters_college, organizations, department, title, profile_image } = profilestate;
        
const formdata = new FormData();
         
formdata.append('dob', dob);
formdata.append('city', city);
formdata.append('state', state);
formdata.append('country', country);
formdata.append('school', school);
formdata.append('board', board);
formdata.append('age', age);
formdata.append('gender', gender);
formdata.append('degree_college', degree_college);
formdata.append('masters_college', masters_college);
formdata.append('organizations', organizations);
formdata.append('department', department);
formdata.append('title', title);
formdata.append('profile_image', profile_image);

const response = await fetch(Constants.url + 'auth/addUserDetail', {
        method: 'POST',
        headers: {
              'Content-type': 'application/json',
                'Authorization': `Bearer ${JSON.parse(localStorage.getItem('token'))}`
            },
         body: formdata
       });
const result = await response.json();
       if (result.status === 'success') {
            hideLoader()
           toast.success(result.message);
       }
        else {
            hideLoader()
            toast.error(result.message);
             return false;
        }

anyone can help me out in this i am getting data as null array i am using formData in hooks any help would be appreciated.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

you are using the formData outside of any function, this would initialize the formData with the initial value of your state i.e. profileState which is empty strings. Initialising formData with empty string results in undefined or null values.

So you should wrap the entire formData part that is outside any function into another single function like handleSubmition which will be triggered when the user upload any form from your component.

const handleSubmition = (e) => {
  e.preventDefault();
  const formdata = new FormData();

  formdata.append('dob', dob);
  formdata.append('city', city);
  formdata.append('state', state);
  formdata.append('country', country);
  formdata.append('school', school);
  formdata.append('board', board);
  formdata.append('age', age);
  formdata.append('gender', gender);
  formdata.append('degree_college', degree_college);
  formdata.append('masters_college', masters_college);
  formdata.append('organizations', organizations);
  formdata.append('department', department);
  formdata.append('title', title);
  formdata.append('profile_image', profile_image);

  const response = await fetch(Constants.url + 'auth/addUserDetail', {
    method: 'POST',
    headers: {
      'Content-type': 'application/json',
      'Authorization': `Bearer ${JSON.parse(localStorage.getItem('token'))}`
    },
    body: formdata
  });
  const result = await response.json();
  if (result.status === 'success') {
    hideLoader()
    toast.success(result.message);
  } else {
    hideLoader()
    toast.error(result.message);
    return false;
  }
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

const addUser= async ()=>{
        const api_url = Constants.url + 'auth/addUserDetail';
        const config = {
         headers: {
           contentType: 'application/json',
          'Authorization': `Bearer ${JSON.parse(localStorage.getItem('token'))}`
           
          }
        }
        const response = await axios.post(url, {...profilestate},config);
        console.log(response.data); //get the response
        /* do rest of stuff */
} 

No need to use the form data at all. Api just expect the form body in form of object that you can easily send via axios. You already have local state object that contains all the data. I hope the above idea would help you to figure out and simplify the problem.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda