简体   繁体   中英

Why adding spread operator make code returns empty array?

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??

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM