How can i seperate my fetch request to another file in react js

am using react and trying access the promise object which is defined in one file (service file) from another file (class component) .but when am importing the getData to another file ,it gives me undefined. Can someone help me out in this.

service.js file
export const getData=()=>{
    fetch('url', {
                method:'Get',
            })
            .then(data=> {
             return   data.json()
            })
           
}

component file 
import {getData} from '../Service'
console.log(getData()) //gives undefine

Upvotes: 0

Views: 2740

Answers (2)

nilemandal
nilemandal

Reputation: 30

component file

let getFetch = async () => {
   const url = "https://jsonplaceholder.typicode.com/todos";
   let res = await getRequestData(url);
   console.log(res)
}
getFetch();

service.js

const getRequestData = async (url) => {
    let resData = await fetch(url)
                        .then( res => res.json() )
                        .then( async (result) => {
                                                    return result
                                                } ,
                                    (error) => { 
                                                return error 
                                                });
    return resData;
}

export default getRequestData;

Upvotes: 0

tan2cang00
tan2cang00

Reputation: 11

you should return data in function getData

    service.js file
export const getData=()=>{
  return fetch('url', { // add return here
                method:'Get',
            })
            .then(data=> {
             return   data.json()
            })
           
}

component file 
import {getData} from '../Service'
console.log(getData()) //gives undefine

Upvotes: 1

Related Questions