1

Now, i am creating a book tracking app using react and redux, i need to fetch data asynchronously, and now i have 3 versions of code two of them return the expected result but not the third

The first one:

import { FETCH_BOOKS } from '../actions/Types.js';

import * as BooksAPI from '../BooksAPI'

export const bookReducer = (state = [], action) => {
   switch(action.type) {
      case FETCH_BOOKS:
         console.log (BooksAPI.getAll().then(books => books))

      default: 
         return state;
 }
}
//Promise {<pending>}
//this returns a promise in a pending state that is resolved to array of objects(expected)

The second one:

import { FETCH_BOOKS } from '../actions/Types.js';

import * as BooksAPI from '../BooksAPI'

export const bookReducer = (state = [], action) => {
  switch(action.type) {
     case FETCH_BOOKS:
        console.log ([BooksAPI.getAll().then(books => books)])

     default: 
        return state;
 }
}
//[promise]
//this returns an array of a promise that is resolved to array of another array of books objects(expected)

The third one:

import { FETCH_BOOKS } from '../actions/Types.js';

import * as BooksAPI from '../BooksAPI'

export const bookReducer = (state = [], action) => {
   switch(action.type) {
      case FETCH_BOOKS:
         console.log ([...BooksAPI.getAll().then(books => books)])

      default: 
         return state;
 }
}
//[]
//this returns an empty array, no promise
//expected spreading items of the returned array of objects not empty array!!

So what is wrong here??

3
  • 2
    Actually your third snippet will not even work because a Promise is not iterable. Commented Sep 28, 2018 at 2:31
  • That is right!! is there a way to achieve that @Derek 朕會功夫 Commented Sep 28, 2018 at 2:32
  • @SaherElgendy You're doing a thing that doesn't make sense from JS perspective, and no, there's no way to achieve that. There wouldn't be a bunch of middlewares like the answer lists if this would be possible with Redux itself. Consider using redux-promise if you want to address specifically promises. Commented Sep 28, 2018 at 8:08

1 Answer 1

2

This isn't directly an answer to your question, but i wanted to point out that reducers need to be synchronous. If you want to do async stuff with redux you'll need to include an async middleware. Some popular options are:

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.