0

I'm trying to export an axios call from an external file to my component, in useEffect. Im exporting the function and importing in the said component. The response is "undefined".

api_call.js:

import axios from 'axios';

const accessToken = window.localStorage.getItem('accessToken')

export const getPublicCircles = async () => {
    const headers = {
      'Content-Type': 'application/json',
      'Accept-Language': 'fr',
      'Authorization': `Bearer ${accessToken}`,
    }
    await axios.get('https://myurl.com/api/this-info', { headers })
      .then(response => console.log(response)) 
      .catch(error => console.log('error', error))
  };

( I also tried with .then((response) => return response.data.data)

component.js

import * as  API from '../../api/api_call';

export default function PublicCircles() {

  const [circles, getCircles] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      const response = await API.getPublicCircles();
      const json = await response.json();
      console.log(response)
      getCircles(response);
    }

    fetchData()
      .catch(console.error);;
  }, []);

  return (
    <Box>
      {circles === '' ? null :
      <PublicCircle circles={circles} />}
    </Box>
  )
}

Here are the results (getting the info from the api_call.js file, not the PublicCirlces.js one. enter image description here Thank you.

Yohav Rn
  • 159
  • 1
  • 11
  • If you want to receive a response in the useEffect 'response' you have to return the response from main the API call. – Ritankar Bhattacharjee May 09 '22 at 20:31
  • 1
    I'd like to point out that is a bad practice to use `await` together with then/catch chaining. This can create confusion about the return value. See https://stackoverflow.com/questions/55019621/using-async-await-and-then-together – Rusurano May 09 '22 at 20:33
  • You also don't return the contents of `axios.get` in your `getPublicCircles` function, you just await for it without storing anything anywhere. – Rusurano May 09 '22 at 20:35
  • @RitankarBhattacharjee Good catch! :) But be careful: the topic starter may use `return await` which isn't the same as returning the value after awaiting: https://eslint.org/docs/rules/no-return-await – Rusurano May 09 '22 at 20:37
  • How should I do? I also did .then((response) => return response.data.data) instead and it did not work either – Yohav Rn May 09 '22 at 20:37
  • 2
    @YohavRn instead of `await axios.get('https://myurl.com.....` use `const data = await axios.get('https://myurl.com......`, and in the next line add `return data`. – Rusurano May 09 '22 at 20:39
  • @Rusurano I get what you pointed out. Thanks , I completely overlooked that. My bad – Ritankar Bhattacharjee May 09 '22 at 20:40
  • @Rusurano it worked thank you, wanna put it as an answer? – Yohav Rn May 09 '22 at 20:41
  • @YohavRn Sure! I'll compile an answer now. – Rusurano May 09 '22 at 20:42

1 Answers1

2

The real problem here is that the function getPublicCircles returns nothing, which is why any variable to which the result of this function call is assigned as a value, will be undefined per JavaScript rules, because a function that doesn't return any value will return undefined.

It's not a good idea to use async/await and then/catch in handling a promise together. Below is the example of handling it correctly with try/catch and async/await:

export const getPublicCircles = async () => {
    const headers = {
      'Content-Type': 'application/json',
      'Accept-Language': 'fr',
      'Authorization': `Bearer ${accessToken}`,
    }
    
    try {
        const data = await axios.get('https://myurl.com/api/this-info', { headers });

        return data;
    } catch(error) {
        console.error('error',error);
    }
}
Rusurano
  • 444
  • 5
  • 12
  • And then how to use it in the useEffect hook? In different component? I'm trying nad no positive results – Time Buy May 02 '23 at 12:46