0

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

1 Answer 1

3

You're missing a return in your PostService:

import instance from "./api";

export default {
  getPost: () => {
    return instance({
      method: "GET",
      url: "/posts"
    })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        return err;
      });
  }
};

Without the return, PostService is calling the api and fetching the data, but it's not sending anything back to your fetchData function calling it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.