0

Requirements

  • I want to use a separate file for the process to access the API

  • I want to use async / await

  • I want to use axios

The code below will be undefined

  • test.js
import fetchApi from '../lib/store';

export default function() {

  async function call() {
    const res = await fetchApi();
    console.log(res);//undefined
  }
  call();
}
  • lib/store.js
import axios from "axios"

export default function() {
  async function fetchApi() {
    try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
        return response;
    } catch (error) {
        return error;
    }
  }
}
y2UcDgAL
  • 31
  • 6

1 Answers1

1

You're not exporting the fetchApi function. You've wrapped it in an anonymous function that does nothing, and therefore returns undefined. You're looking for

import axios from "axios"

export async function fetchApi() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
    return response;
  } catch (error) {
    return error; // btw, don't do that.
  }
}

import { fetchApi } from '../lib/store';

export default async function call() {
  const res = await fetchApi();
  console.log(res);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375