I just started to experiment with react and redux and I face couple of issues on the way.
When I try to render async data on route change the dispatched action is getting fired twice. First is undefined and than comes the real data.
Here is my store
import { createStore, combineReducers, applyMiddleware } from 'redux' import createLogger from 'redux-logger' import thunk from 'redux-thunk' import { routerReducer, routerMiddleware, push } from 'react-router-redux' import reducers from '../reducers' import { browserHistory } from 'react-router'; const middleware = [ thunk ]; if (process.env.NODE_ENV !== 'production') { middleware.push(createLogger()); } middleware.push(routerMiddleware(browserHistory)); // Add the reducer to your store on the `routing` key const store = createStore( combineReducers({ reducers, routing: routerReducer }), applyMiddleware(...middleware), ) export default store; reducer
export const RESOLVED_GET_PROFILE = 'RESOLVED_GET_PROFILE' const profileReducer = (state = {}, action) => { switch (action.type) { case 'SET_PROFILE': return {profile: action.profile} default: return state; } }; export default profileReducer; actions
import * as types from './actionTypes'; import Api from '../middleware/Api'; export function getProfile() { return dispatch => { dispatch(setLoadingProfileState()); // Show a loading spinner Api.get('profile').then(profile => { dispatch(doneFetchingProfile); dispatch(setProfile(profile)); }).catch(error => { dispatch(showError(error)); throw(error); }); } } function setProfile(data) { return { type: types.SET_PROFILE, profile: data } } function setLoadingProfileState() { return { type: types.SHOW_SPINNER, loaded: false } } function doneFetchingProfile() { return { type: types.HIDE_SPINNER, loaded: true } } function showError() { return { type: types.SHOW_ERROR, loaded: false, error: 'error' } } and here is my component
import React, {PropTypes, Component} from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import * as profileActions from '../../../actions/profileActions'; class Profile extends Component { static propTypes = { profile: PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { profile:{ username: '', password: '', email: '' } } this.onUpdate = this.onUpdate.bind(this) } onUpdate(event) { alert() } componentDidMount() { //here I dispatch the action this.props.actions.getProfile() } componentWillReceiveProps(nextProps) { } render() { console.log(this.props) //this.props.profile on first is undefined and then filled const { profile } = this.props.profile return ( <div> </div> ); } } function mapStateToProps(state) { return { profile: state.default.profile, }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(profileActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(Profile); what do I wrong?
