Home > Blockchain >  I am not getting the data expected from the api call instead I get undefined
I am not getting the data expected from the api call instead I get undefined

Time:08-10

I have this file I call PostAPi.js where I have all my functions and then in my Posts.js where I make the call.

api.getPosts() and data in the Posts.js, returns undefined instead of the data.

PostsApi.js

import axios from "axios";

const api = axios.create({  
  baseURL: "https://jsonplaceholder.typicode.com/",
});

export const getPosts = () => {
  api.get("/posts").then((response) => response.data); // console.log(response.data) returns the data which is an array of objects but I keep getting undefined in the Posts.js file.
};

Posts.js

import React, { useEffect } from 'react'
import { useQuery } from "@tanstack/react-query";
import * as api from "./PostApi"

const Users = () => {

  useEffect(() => {
    console.log("posts");
    console.log(api.getPosts()) // returns undefined as well
  }, [])

  const { data } = useQuery("posts", api.getPosts)
  console.log(data) // returns undefined

package.json dependencies

  "dependencies": {
    "@tanstack/react-query": "^4.0.10",
    "@tanstack/react-query-devtools": "^4.0.10",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-query": "^4.0.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  }

CodePudding user response:

In Your PostsApi.js return the promise

export const getPosts = () => {
          return api.get("/posts").then((response) => response.data); // console.log(response.data) returns the data which is an array of objects but I keep getting undefined in the Posts.js file.
        };

And In your Posts.js file consume that promise

useEffect(() => {
        api.getPosts().then((res) => {
          console.log("In APP res", res);
        });
      }, []);

CodePudding user response:

// update your PostApi.js like the following
import axios from "axios";

const api = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com/"
});

export const getPosts = async () => {
  try {
    const response = (await api.get("/posts")).data;
    return response;
  } catch (err) {
    return err.message;
  }
};

// update the following line 
const { data } = useQuery(["posts"], api.getPosts())

  • Related