How to get a resolved promise to my component with Redux Promise?

5.2k Views Asked by At

I'm making a request in my action - pulling from an API that needs to load in some data into my component. I have it start that request when the component will mount, but I can't seem to get Redux-Promise to work correctly because it just keeps returning:

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

in my dev tools when I try to console.log the value inside of my componentWillMount method.

Here's my code below:

Store & Router

import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import routes from './routes';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  applyMiddleware(promiseMiddleware)
);

render(
  <Provider store={store}>
    <Router history={hashHistory} routes={routes} />
  </Provider>,
  document.getElementById('root')
);

Action

import axios from 'axios';

export const FETCH_REVIEWS = 'FETCH_REVIEWS';
export const REQUEST_URL = 'http://www.example.com/api';

export function fetchReviews() {
  const request = axios.get(REQUEST_URL);
  return {
    type: FETCH_REVIEWS,
    payload: request
  };
};

Reviews Reducer

import { FETCH_REVIEWS } from '../actions/reviewActions';

const INITIAL_STATE = {
  all: []
};

export default function reviewsReducer(state = INITIAL_STATE, action) {
  switch(action.type) {
    case FETCH_REVIEWS:
      return {
        ...state,
        all: action.payload.data
      }
    default:
      return state;
  }
}

Root Reducer

import { combineReducers } from 'redux';
import reviewsReducer from './reviewsReducer';

const rootReducer = combineReducers({
  reviews: reviewsReducer
});

export default rootReducer;

Component

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchReviews } from '../../actions/reviewActions';

class Home extends Component {
  componentWillMount() {
    console.log(this.props.fetchReviews());
  }

  render() {
    return (
      <div>List of Reviews will appear below:</div>
    );
  }
}

export default connect(null, { fetchReviews })(Home);

Any and all help is greatly appreciated. Thank you.

1

There are 1 best solutions below

1
On BEST ANSWER

Redux-promise returns a proper Promise object, so you may change your code a little bit to avoid immediate execution.

class Home extends Component {
  componentWillMount() {
    this.props.fetchReviews().then((whatever) => { console.log('resolved')})
  }
  // ...
}