When I try to make axios request in useEffect hook, it returns undefined,
but I find it's successful when viewing in Network request in Inspect Mode
api.js
import axios from "axios";
export default axios.create({
baseURL: `https://jsonplaceholder.typicode.com`
});
PostService.js
import instance from "./api";
export default {
getPost: () => {
instance({
method: "GET",
url: "/posts"
})
.then((res) => {
return res;
})
.catch((err) => {
return err;
});
}
};
App.js
import "./styles.css";
import { useEffect } from "react";
import PostService from "./PostService";
export default function App() {
useEffect(() => {
async function fetchData() {
const response = await PostService.getPost();
console.log(response); //return undefined
}
fetchData();
}, []);
return (
...
);
}
CodeSandBox:
https://codesandbox.io/s/happy-leftpad-cz12i?file=/src/App.js