Putting an axios call in a function but in another file and calling it when needed

import axios from 'axios';

export default axios.get({
  baseUrl: `https://api.github.com/users/`,
  responseType: 'json',

import React, { useState } from 'react';
import API from './utils/API';

const Form = (props) => {
  const [userName, setUserName] = useState('');

  const handleSubmit = async (event) => {

    const resp = await API.get(`/${userName}`);

The last line on the code here in Form.js is throwing an error. I am trying to concatenate the base url of the api call with the userName which is a value from an Input element.

You just need to adjust a few things


export const getUser = (username) => axios.get({
// code

import * as  API from './utils/API';

// ..

const resp = await API.getUser(userName);

When you import like this import API from './utils/API'; you are importing the default export which in your case is the get call. The export appears to be a function invocation, not a callback. That’s why I changed it to be more like this export const getUser = (username) => axios.get.

export default axios.get({
  baseUrl: `https://api.github.com/users/`,
  responseType: 'json',
1 Like

So sorry for responding late. I am impressed by your response and clear explanation but also, one of the reasons for the error I was encountering was because I was calling axios.get({…)}, two times. That is, both in API.js and also in Form.js. When among other changes, I changed the axios.get({…)} in API.js to axios.create({…)} and then in Form.js, I call the api with API.get({…)}, the code ran correctly and gave the expected response.

I see that with your code, I will not be calling axios.get({…)} twice which I believe should work correctly. Thanks a lot.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.