-1

I'd like to create an external function that fetch data and return the result.
But I can't make it work, here's my function:

// Request.js:

import React from 'react'

import { authHeader } from "../../jwt/_helpers/auth-header";
import { handleResponse } from "../../jwt/_helpers/handle-response";

export default function Request(method,request) {
   const requestOptions = {
        method: method,
        withCrendtials: true,
        headers: authHeader(),
   };
   fetch(process.env.REACT_APP_API + request, requestOptions)
        .then(handleResponse)
        .then(
            (result) => {
                console.log(result); // This returns an object
                return result // This returns undefined
            },
            (error) => {
                return error
            }
        );
}

Then I use it like so:

// Main.js:

import Request from './Request';

let obj = Requete("GET", "/myPath/myQuery");
this.setState({foo: obj.items});

In my Request.js file, i'm logging the result and I get the right object, then I return it and In my Main.js I get an undefined value for that function.

If I copy my code from Request.js to my Main.js it works fine...
But my code gets unreadable with fetch queries taking almost 20 lines each...
Any ideas?

Durgesh Pal
  • 695
  • 5
  • 13
Sacha APK
  • 21
  • 3
  • `return result` doesn't "return undefined." `obj.items` is undefined because `obj` is an unresolved `Promise` instance. – benbotto Jul 08 '20 at 15:06
  • Can you add your code inside code sample tags please – Pablo Salazar Jul 08 '20 at 15:07
  • 4
    The problem is that your `Request` function doesn't return anything. The `then` callback returns the object just fine - but only causes the promise to resolve. – Bergi Jul 08 '20 at 15:09

1 Answers1

2

Try returning the fetch from the exported function, and using a .then in main.js to wait for the result before using it in setState:

export default function Request(method, request) {
  const requestOptions = {
    method: method,
    withCrendtials: true,
    headers: authHeader(),
  };
  return fetch(process.env.REACT_APP_API + request, requestOptions)
    .then(handleResponse)
    .then(
      (result) => {
        console.log(result); // This returns an object
        return result; // This returns undefined
      },
      (error) => {
        return error;
      }
    );
}
// Main.js:
import Request from './Request';

Request("GET", "/myPath/myQuery").then(obj => {
  this.setState({foo: obj.items});
})

The explanation is the exported function "Request" returns BEFORE the fetch has completed, but it was returning nothing (undefined) as there was no return statement. Adding the return statement makes it return something: the promise returned by the second then attached to the initial fetch. In main.js, we call the .then method of this promise with a function, and this function is given the result (obj) of the promise when the latter resolves. It can then do what it likes with it. (You can think of the body of the .then function as existing in a timeframe later than the surrounding code, and AFTER the fetch has completed).

phhu
  • 1,462
  • 13
  • 33