Search code examples
reactjsaxiosuse-effect

Using Axios in useEffect from an external file


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.


Solution

  • 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);
        }
    }