kobowo
kobowo

Reputation: 2787

React Redux Mapping state to props not working

So I'm trying to learn React with Redux and so far I think I've been able to work out most of the code needed to make it work but I'm having an issue with getting my state passed down to my component. I am using Visual Studio 2017's ASP.NET Core project template that has react and redux boilerplate codes and they used this:

export default connect(
  state => state.weatherForecasts,
  dispatch => bindActionCreators(actionCreators, dispatch)
)(FetchData);

I tried doing the same thing with my own component like so:

export default connect(
  state => state.lecture,
  dispatch => bindActionCreators(actionCreators, dispatch)
)(LectureTable);

but when trying to access the contents of my props, the properties I want to get are tagged as undefined. I checked through Redux devtools that my initial state exists but my component is unable to see the props I'm trying to pass to it. The weird thing is I just imitated the boilerplate code but it isn't working yet the boilerplate code works just fine (ie I can go to the component and log out its initial state).

Since I'm following the format used by Visual Studio,my actioncreators, reducers, and constants are in one file shown below:

const GET_LECTURES = "GET_LECTURES";

const initialState = {
    lectures: [],
    selectedLecture: {},
    isLoading: false,
    test: 0
};

export const actionCreators = {
    requestLectures: isLoading => async (dispatch) => 
    {    
      if (!isLoading) {
        // Don't issue a duplicate request (we already have or are loading the requested data)
        return;
      }

      dispatch({ type: GET_LECTURES });

      const url = `api/lecture/`;
      const response = await fetch(url);
      const lectures = await response.json();

      dispatch({ type: RECEIVE_LECTURES, payload: lectures });
    } 
  };

export const reducer = (state = initialState, action) => {
    switch (action.type) {
    case GET_LECTURES:
        return { ...state, isLoading: true }; 
        default:
        return state;
    }
};

I'm sorry if its all messy. I'm really just starting to begin to understand redux..

Edit My component code:

import React, { Component } from 'react';
import {Button, Table, Label, Menu, Icon} from 'semantic-ui-react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {actionCreators} from './../../store/Lecture';

export class LectureTable extends Component {

  componentWillMount(){
   // this.props.requestLectures(this.props.isLoading);
    console.log(this.props.test);
  }

  render() {
    return (
        <Table size='large'>
        {/*removed to make it cleaner..currently only has static data too lol*/}
      </Table>
    )
  }
}



export default connect(
  state => state.lecture,
  dispatch => bindActionCreators(actionCreators, dispatch)
)(LectureTable);

where my store is configured:

import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import { routerReducer, routerMiddleware } from 'react-router-redux';
import * as Lecture from './Lecture';
import * as Counter from './Counter';
import * as WeatherForecasts from './WeatherForecasts';

export default function configureStore(history, initialState) {
  const reducers = {
    lecture: Lecture.reducer,
    counter: Counter.reducer,
    weatherForecasts: WeatherForecasts.reducer
  };

  const middleware = [
    thunk,
    routerMiddleware(history)
  ];

  // In development, use the browser's Redux dev tools extension if installed
  const enhancers = [];
  const isDevelopment = process.env.NODE_ENV === 'development';
  if (isDevelopment && typeof window !== 'undefined' && window.devToolsExtension) {
    enhancers.push(window.devToolsExtension());
  }

  const rootReducer = combineReducers({
    ...reducers,
    routing: routerReducer
  });

  return createStore(
    rootReducer,
    initialState,
    compose(applyMiddleware(...middleware), ...enhancers)
  );
}

my index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createBrowserHistory } from 'history';
import configureStore from './store/configureStore';
import App from './pages/App';
import registerServiceWorker from './registerServiceWorker';

// Create browser history to use in the Redux store
const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const history = createBrowserHistory({ basename: baseUrl });

// Get the application-wide store instance, prepopulating with state from the server where available.
const initialState = window.initialReduxState;
const store = configureStore(history, initialState);

const rootElement = document.getElementById('root');

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  rootElement);

registerServiceWorker();

Upvotes: 3

Views: 6761

Answers (6)

kobowo
kobowo

Reputation: 2787

I found the solution. First of all I'm a noob both to stackoverflow and to react so I apoligize for all my inconsistencies (if thats the right term?).

What I found out:

  1. I am using react router
  2. I was doing the connect method to a subcomponent of the component being rendered by the router
  3. I placed the connect method to the parent component and it worked

Some notes:

  • state => state.lecture still works
  • I will take all of your advices to heart and change my code accordingly
  • The only reason I was adamant with solving the problem using the code I had was because I couldn't accept the fact that boilerplate code wouldn't work unless I had done something specifically different from what the boilerplate did. I just didn't take into account that the router played a huge role with it.
  • I repeat...I'm a react noob so I'm sorry for wasting your time T_T

Edit again: I was able to connect a different child component with the Redux store. I'm trying to look at why I still can't do it for that specific component that caused me to ask this question. I'll update my answer once I find the reason.

Upvotes: 2

devserkan
devserkan

Reputation: 17638

You have two problems here.

You are defining mapStateToProps function as the first argument to connect wrong. As many of answers explain this now you should use it like, this:

export default connect(
  state => ( { lecture: state.lecture } ),
  dispatch => bindActionCreators(actionCreators, dispatch)
)(LectureTable);

Now, you have a lecture prop as your state. You can reach it with this.props.lecture. But in your componentWillMount method, you are trying to log it like this.props.test. It should be this.props.lecture.test.

By the way, try to use componentDidMount instead of componentWillMount since it will be deprecated in the future releases.

Upvotes: 0

Mehrnaz.sa
Mehrnaz.sa

Reputation: 386

I think by doing the following steps, you can solve the issue:

  1. First you need to call two functions when you want to connect your component to application state, one is mapDispatchToProps and another one is mapStateToProps, for your code to be clean, its better to define these functions separately and then pass them by name to connect, but if you want to use your own way you should do these changes: (assuming your reducer name is lecture from your combineReducers, and assuming you are calling requestLectures with this syntax: this.props.lectureActions.requestLectures() and importing lectureActions from the file you have written lecture related actions) :

    export default connect(
    state => state.lecture.lectures,
    dispatch => {lectureActions: bindActionCreators(lectureActions, dispatch)}
    )(LectureTable);
    
  2. from above code, you do not need to export an object that contains the actions like actionCreators, you should export the requestLectures function out of it independently

  3. add below case to your reducer so that when getting the lectures succeeds the state of the application gets updated with the lectures:

    case RECEIVE_LECTURES:
      return { ...state, isLoading: false, lectures: payload.lectures }; 
      default:
      return state;
     }
    

Upvotes: 0

Davo
Davo

Reputation: 986

Rick, your connect argument should be something like:

export default connect( state => {
    return {
      test: state.lecture // Or any value
    }
})(LectureTable);

You're trying to console log the test prop, so you should include it in your connect call.

Upvotes: 1

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18173

I think in their example weatherForecasts is an object. In your example lectures seems to be an array so I suggest to rewrite your mapStateToProps function like this if you only need to get the lectures prop

state => ({ lectures: state.lectures})

if you need the whole state you can have state => state so you can access the props this.props.test and this.props.lectures

Keep in mind that mapStateToProps should return an object, not an array. By the way, in your reducer the field name is lectures (plural) not lecture so state => state.lecture will be undefined

Upvotes: 1

SamVK
SamVK

Reputation: 3435

The first argument to connect() should be a function that returns an object - with the props you want added as keys, and their value being the value from state. e.g.

state => ({ lecture: state.lecture })

Upvotes: 2

Related Questions