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

126
Vistas
why can't my first post request success on react native custom hooks with axios?

my custom hooks :

import { useContext, useState } from "react";
import { AppContext } from "../context/app.context";

const usePostAxios = (url) => {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  const { setUrl, token } = useContext(AppContext);

  const postData = async (data) => {
    try {
      setIsLoading(true);
      axios.defaults.headers.common["X-Authreq"] = token;

      await axios
        .post(`${setUrl}/${url}`, data)
        .then(({ data }) => {
          setData(data);
        })
        .catch((err) => {
          setError(err.response || err.request);
        });

      setIsLoading(false);
    } catch (err) {
      console.log(err);
    }
  };

  return [isLoading, postData, data, error];
};

export { usePostAxios };

for posting data :

const [isPosting, postFun, res, err] = usePostAxios("/apidet/EmpLog");

const handleSubmit = async (val) => {
    await postFun({
      UserName: val.email,
      password: val.pass,
    });

    if (res) {
      const { Apd, Apt } = res.ResponseData;
      dispatch({ type: "APP-LOGIN", token: `${Apd}:${Apt}` });
      setIsError(false);
      navigate("Home");
      return;
    } else {
      setIsError(true);
      return;
    }
  };

then why my code is getting in else block and getting error but when i press submit button again the code run successfully and my login process success

so why is my code not running on first try ?

am i doing something stupid ?

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

0

Well, wrote in this way, basically, when this this code is excecuted

if(res) {  
  // Something to do with result
}

the variable res has null as value, initially.

You should check for changes in res with useEffect instead, like:

useEffect(()=> {
  if(res) {
    // Something to do with result
  }
}, [res])
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