Tr4nsf3r
Tr4nsf3r

Reputation: 33

React/Redux accessing props

I have a doubt on how to access fields inside the Redux state in a React component:

Reducer.js

import { fromJS } from 'immutable';
import { combineReducers } from 'redux';
import {
  LOAD_HEADERS_SUCCESS,
  LOAD_HEADERS_ERROR
} from '../constants';

const initialState = fromJS({
  posts: []
});

const homeReducer = (state = initialState, action) => {
  switch(action.type) {
    case LOAD_HEADERS_SUCCESS:
      return Object.assign({}, state, {
        posts: action.payload
      });
    case LOAD_HEADERS_ERROR:
      return state;
    default:
      return state;
  }
};

const rootReducer = combineReducers({
  homeReducer
});

export default rootReducer;

I use redux-saga to handle extrnal API call

Sagas.js

import { call, put, takeEvery, takeLatest, all } from 'redux-saga/effects';
import { fetchHeaders } from '../api';
import { loadHeaderSuccess, loadHeaderError } from '../actions';

import {
  LOAD_HEADERS_REQUEST,
} from '../constants';


function* loadPostsHeader(action) {
  try {
    const response = yield call(fetchHeaders);
    yield put(loadHeaderSuccess(response.data));
  } catch (error) {
    yield put(loadHeaderError(error));
  }
}

function* headerSaga() {
  yield takeLatest(LOAD_HEADERS_REQUEST, loadPostsHeader);
}

export default function* rootSaga() {
  yield all([
    headerSaga()
  ]);
}

HomePage.js

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

import H2 from '../../components/H2';
import Section from './Section';
import PageBlock from '../../components/PageBlock';
import P from '../../components/P';

import { loadHeaderRequest } from '../../actions';

class HomePageContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function
  componentDidMount() {
    this.props.onHomeLoad();
  }

  render() {
    const { posts } = this.props;

    return (
      <div>
        <PageBlock>
            <div>
                <H2>
                  Latest Articles
                </H2>
                <P>
                  { posts != undefined ? posts[0].title : 'ERR' }
                </P>
            </div>
        </PageBlock>
      </div>
    );
  }
}

HomePageContainer.PropTypes = {
  posts: PropTypes.array,
  onHomeLoad: PropTypes.func
};

const mapStateToProps = state => {
  console.log(state.homeReducer.posts);
  return { posts: state.homeReducer.posts };
};

const mapDispatchToProps = dispatch => {
  return {
    onHomeLoad: () => {
      dispatch(loadHeaderRequest());
    }
  };
};

const HomePage = connect(mapStateToProps, mapDispatchToProps)(HomePageContainer);

export default HomePage;

The problem is in mapStateToProps: if I use state.homeReducer.posts everything works, otherwise if I try state.posts, posts is always undefined.

I have seen many example where the field is accessed directly without the name of the reducer in the middle.

I wonder why this is not the case in my code.

Thanks!

Upvotes: 3

Views: 1575

Answers (2)

Chaitanya Mankala
Chaitanya Mankala

Reputation: 1704

If you want all reducers in a single module, you can directly use state.posts, for that you can just drop combineReducers

const rootReducer = homeReducer;

export default homeReducer;

Upvotes: 0

dfsq
dfsq

Reputation: 193301

I use state.homeReducer.posts everything works, otherwise if I try state.posts, posts is always undefined.

You set up it like this. homeReducer is a subbranch in your state tree. You need to use it in order to access it's data. But it's better to call it differently, e.g.:

const rootReducer = combineReducers({
  home: homeReducer
});

Then you would use state.home.posts.

Upvotes: 1

Related Questions