skip to Main Content

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)
  })()

3

Answers


  1. Chosen as BEST ANSWER

    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();
      },[])
    

  2. 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);
      })()
    
    Login or Signup to reply.
  3. 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)
                }
            )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search