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

157
Views
React Native get return value of async function

I am trying to get pub locations data from MYSQL server and my fetch function works well. But after that, this try-catch block does not return anything. I also tried without try-catch block but it does not change anything

  getPubsFromDatabase = async () => {
    let response = await fetch(fetchDataUrl, {
      method: 'POST',
      headers: 
      {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
      },
    });
    try{
      let json = await response.json();
      console.log(json)
      return json;
    }
    catch (error) {
      console.log(error);
    }
  }

And here, I am trying to get the return value of the function. But in this version, I cannot even see any console.log output. What I mean by the version is, if I put 2nd line out of the async block without "await" keyword, I can see the console.log but I it gives "undefined" then.

  (async () => {
    const locationsData = await getPubsFromDatabase();
    console.log(locationsData)
  })()

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can use then and catch in the function fetch.

  const getPubsFromDatabase = () => {
    return fetch(fetchDataUrl, {
      method: 'POST',
      headers: 
      {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
      },
    }).then(async (response) => {
      const json = await response.json().then((data)=>{
        return data;
      }).catch((err)=>{
        console.log('error from json method: ',err);
        return  { error: {
         message: 'error from json method',
         object: err
        }};
      });
      console.log(json);
      return json;
    }).catch((error) => {
      console.log('error from request: ', error);
      return  {
        error: {
          message: 'error from request', object: error
        }
      };
    });
  }

And when you use the method getPubsFromDatabase would be of the next way:

  (async () => {
    const locationsData = await getPubsFromDatabase();
    console.log(locationsData);
  })()
about 4 years ago · Santiago Trujillo Report

0

You can use Promise to return either result or error, In the example given below i have used axios library but you can also try same with fetch api For Example

export const getData = () => {

  return new Promise((resolve, reject) => {
    const url = ApiConstant.BASE_URL + ApiConstant.ENDPOINT;
    const API_HEADER = {
      "Authorization": token,
    };

    axios
      .get(url, {
        headers: API_HEADER,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((error) => {
        // handle error
        reject(error);
        console.log(error);
      });
  })
}

You can call the above function in component or screen like this:

getData().then(
            (data) => {

            }
        ).catch(
            error => {
                console.log(error)
            }
        )
about 4 years ago · Santiago Trujillo Report

0

I solved the problem by instead of returning the value from the function, I set the value inside the function. This seems to work now.

  const [locationsData, setLocationsData] = useState();
  getPubsFromDatabase = async () => {
    let response = await fetch(fetchDataUrl, {
      method: 'POST',
      headers: 
      {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
      },
    });
    try{
      let json = await response.json();
      setLocationsData(json); // Here, I changed the value of the locationsData instead of returning
    }
    catch (error) {
      console.log(error);
    }
  }

And to call the function:

  useEffect(()=> {
    getPubsFromDatabase();
  },[])
about 4 years ago · Santiago Trujillo 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!