0

I have a backend I'm building for a class project, and I'm able to successfully post to it's DB using the following:

export function postToAPI(data) {
  return fetch('http://localhost...', {
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json',
    },
    redirect: 'follow',
    referrer: 'no-referrer',
    body: JSON.stringify(data),
  })
    .then(response => {
      return response.json();
    })

After it posts to the DB, I want to grab that json and then push that to the Redux store. It's returning 'response.json() if it's successful, but when I console log the response it comes out as a promise, not a json object. What am I doing wrong?

I can see that the promise returns successfully in console log, but I can't figure out how to actually get the data out of it to actually post it to my redux.

I'm using a middleware that will check the action type and see if it's one to update the DB with a post action, and if so, first update the DB, get the ID from the returned JSON, and then push that info to redux, but I just can't for the life of me get the data to get out of the promise that's returned. I thought the .json() function did that, but I'm lost at this point.

I get this in response from console logging the return of that function shown above:

promise result screenshot

glitchwizard
  • 421
  • 1
  • 6
  • 23
  • 2
    `.then` always returns a promise. *"I can't figure out how to actually get the data out of it to actually post it to my redux. "* You have access to the data **inside** the `.then` callback. You cannot magically unwrap the promise in another way. `fetch` is asynchronous. – Felix Kling Mar 11 '19 at 20:39
  • See also https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Estus Flask Mar 11 '19 at 20:44
  • @FelixKling so I have to dispatch from inside the 'then' function? How do you do that and keep your code DRY? Right now I have middleware in there trying to update the action after the 'then' is completed. So I can now verify that the JSON is being put in the action payload, then I call ``` next(action) ``` on the updated payload, but it doesn't seem to want to update redux still – glitchwizard Mar 11 '19 at 20:58
  • It certainly works, but hard to know what the issue is without seeing your code. Maybe have a look at https://redux.js.org/advanced/async-flow and look at the implementation of the mentioned middlewares. – Felix Kling Mar 11 '19 at 21:02
  • @FelixKling ok I think I don't have my async stuff in the right order then. I'll need to tweak that. I am now able to get the JSON response, though still can't get it to update redux just yet. Thanks for the help! – glitchwizard Mar 11 '19 at 21:25

0 Answers0