Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!