React Redux Mapping state to props not working - javascript

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();

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 })

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:
I am using react router
I was doing the connect method to a subcomponent of the component being rendered by the router
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.

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

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.

I think by doing the following steps, you can solve the issue:
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);
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
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;
}

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.

Related

How to update React component after changing state through redux?

I was learning React and Redux and while doing that I decided to make webpage with a button which on clicking would change the state. Below the button I wanted to display the current state in a different component. Though the button on clicking changes the state, but it is not getting reflected in the component. Here is my code:
App.js
import React from 'react'
import Name from './Name'
import {changeName} from './Action';
export default function App () {
return (
<div>
<button onClick={changeName}>Click me</button>
<Name />
</div>
)
}
Name.js
import React from 'react'
import {store} from './Store'
function Name(props) {
return (
<div>
My name is: {store.getState()}
</div>
)
}
export default Name
Store.js
import { createStore } from 'redux';
import {reducer} from './Reducer';
export const store = createStore(reducer, 'Tarun');
Action.js
import {store} from './Store';
export const changeName = () => {
if (store.getState() === "Tarun"){
store.dispatch({ type: 'name', payload: 'Subhash' });
}
else{
store.dispatch({ type: 'name', payload: 'Tarun' });
}
}
Reducer.js
export const reducer = function(state, action) {
if (action.type === 'name') {
return action.payload;
}
return state;
};
When I click the button, The text inside the Name component does not change. What is the issue?
You need to set up your reducer and initial store properly following the Redux documentation.
You're missing a Provider, which will provide your store to your application.
const store = createStore(reducer, applyMiddleware(thunk));
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
Now, your store is available to your components.
Your reducer needs an initial state too and you're always supposed to return an updated copy of your state. That said, don't change the state directly, but make a copy, change it, then return that copy.
const initialState = {
name: ""
};
const reducer = function(state = initialState, action) {
if (action.type === "name") {
return { ...state, name: action.payload };
} else {
return state;
}
};
export default reducer;
You might have noticed that I added a middleware to your store, and that's because it's usually the way to go when accessing your current reducer's state in your actions. That said, I installed redux-thunk for that, so in your action, you can have something like this:
export const changeName = () => {
return (dispatch, getState) => {
if (getState().name === "Tarun") {
dispatch({ type: "name", payload: "Subhash" });
} else {
dispatch({ type: "name", payload: "Tarun" });
}
};
};
Now, with your store being provided to your app, your reducer being done and your actions being ready to go, you can connect different components to your reducer.
You use the high order component in react-redux called connect for that. For example, in your Name component, we can connect the name to be displayed to your reducer by mapping your state to the component's props:
function Name(props) {
return <div>My name is: {props.name}</div>;
}
const mapStateToProps = state => {
return {
name: state.name
};
};
export default connect(mapStateToProps)(Name);
The nice thing here is that you can also leave the first parameter in the connect high order component empty and just pass the second, which would be the dispatch functions. Well, that's what you would do in your App component, you would connect it to the changeName action.
function App(props) {
return (
<div>
<button onClick={props.changeName}>Click me</button>
<Name />
</div>
);
}
const mapDispatchToProps = dispatch => {
return {
changeName: () => dispatch(changeName())
};
};
export default connect(
null,
mapDispatchToProps
)(App);
Now, when App dispatches a changeName action, your reducer state will be updated and the other components that are connected to the reducer's state will re-render.
Summary: Try to think of your store as an empty jar of candies. Your jar starts empty, but different actions could change what's inside the jar. On top of that, different people in the house that know where the jar is can go get some candy. Translating to your problem, your app begins with an empty name and you have an action that sets up a name. The components that know where to find that name by being connected to your reducer will know when that name changes and will get the updated name.
The final code can be found here:
The only way your name component will rerender is its props or state change, or if a parent component rerenders. Making a change in redux will not automatically do this. In order to see changes to the state, you'd need to subscribe to those changes. You could do this yourself, but a far better solution is to use react-redux, which is designed for connecting react components to redux stores.
For example, you'd add a provider to your app:
import { Provider } from 'react-redux';
import { store } from './Store'
export default function App () {
return (
<Provider store={store}>
<div>
<button onClick={changeName}>Click me</button>
<Name />
</div>
</Provider>
)
}
And then you'd use connect with your Name component:
import { connect } from 'react-redux';
function Name(props) {
return (
<div>
My name is: {props.name}
</div>
)
}
const mapStateToProps = (state) => {
return { name: state };
}
export default connect(mapStateToProps)(Name)

React main component is called twice while using redux

I have a react main component that dispatches redux action on componentDidMount, the action will fetch API data.
The problem is: when I start my application my componentDidMount and main component are executed twice. So, it makes 2 API calls for each time application loads. API has a limit for the total number of calls I make, I don't want to reach my limit.
I have already tried fixing the issue by removing constructor, using componentWillMount problem is not solved.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../redux/actions/fetchActions';
import TableHeader from './tableHeader';
class Main extends Component {
componentDidMount() {
console.log("mounted");
// this.props.dispatch(actions.fetchall("market_cap"));
}
render() {
console.log("rendered");
// console.log(this.props.cdata);
// console.log(this.props.cdata.data.data_available);
return <div className="">
<TableHeader {...this.props} />
</div>
}
}
export default Main;
///actions
import axios from 'axios';
export function fetchall(sort) {
return function (dispatch) {
axios.get(`https://cors-anywhere.herokuapp.com/https:-----------`)
.then(function (response) {
dispatch({
type: 'FETCH_DATA',
payload: response.data
})
})
.catch(function (error) {
console.log(error);
})
}
}
//reducer
let initialState = {
coins: [],
data_available: false,
};
export default function (state = initialState, action) {
switch (action.type) {
case 'FETCH_DATA':
return {
...state,
coins: action.payload,
data_available: true
}
default: return state;
}
}
//rootreducer
import { combineReducers } from 'redux';
import DataReducer from './dataReducer';
export default combineReducers({
data: DataReducer
});
////index
import {createStore, applyMiddleware} from 'redux';
import MapStateToProps from './components/mapStateToProps';
import rootReducer from './redux/reducers/rootReducer';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
//const initialState = {};
const middleware = [thunk];
const store = createStore(rootReducer, applyMiddleware(...middleware));
ReactDOM.render(<Provider store={store}><MapStateToProps/></Provider>, document.getElementById("root"));
console image is posted for reference "rendered" is logged inside main component
"runned1" is logged inside main-subcomponent
"mounted" logged inside componentDidMount
"
I believe you can work around this by providing some additional logic in your componentDidmount. You should also make use of your component state.
Write something like this:
constructor(props){
super(props)
this.state = {
mounted: false
}
}
componentDidMount(){
if(!this.state.mounted){
this.props.dispatchmyAction()
this.setState({
mounted: true
})
}
}
This essentially says, if your component has already mounted once, then you will not make your action creator request.
If you watch your console.log carefully you can notice that your HMR Hot Module Reloading -plugin, re-mounts your component and this is the main reason behind this occurrence.
What this plugin does, is that it watches for your bundles code changes and on every time you save re-renders your component. There has been a lot of discussion as well that this plugin does not work all cases as expected.
Here is some material you might consider to go trough if you wish to use HMR.
Writing about HMR -
https://codeburst.io/react-hot-loader-considered-harmful-321fe3b6ca74
User guide for HMR -
https://medium.com/#rajaraodv/webpacks-hmr-react-hot-loader-the-missing-manual-232336dc0d96
The problem is solved when I removed webpack from the project. But can anyone answer how can I solve this while still using the webpack.

Second Redux ##INIT action clears the store state which already was modified with another action

I'm new to React/Redux and not sure if I'm not doing something wrong.
I'm having a component which makes an AJAX call on componentDidMount to fetch data from the server to render.
The problem is that Redux is dispatching two #INIT actions and often the second one is dispatched after I already received the response from the server. It comes with an empty (initial) state which is passed to the component props and, as result, I receive a blank screen.
Please see this log produced by the reducer:
I already found that having two ##INIT actions is an expected behavior, the first one is needed to test the reducers and the second one is an actual init (check the discussion here).
The question is how can I solve this issue in a proper way. Is it a race condition or am I doing something wrong? Thanks!
Update
What is interesting is that it definitely relates to the performance of my laptop. The server is also running on my local environment. To allow me to proceed with development while I'm waiting for the answer I temporarily put setTimeout with 100ms delay into componentDidMount. Now I commented it and can't repro the issue.
Update Adding pieces of my code
Store
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
const middleware = window.devToolsExtension
? compose(
applyMiddleware(thunk),
window.devToolsExtension()
)
: applyMiddleware(thunk);
const store = createStore(reducers, middleware);
export default store;
Reducer (nothing special, just used it to log the action because browser Redux extension shows only one ##INIT action)
import * as types from '../actions/types';
const initialState = {
listings: []
};
export default function(state = initialState, action) {
console.log(action, state);
switch (action.type) {
case types.LISTINGS_FOUND:
return { listings: action.payload };
default: return state;
}
};
Component
import React from 'react';
import { connect } from 'react-redux';
import { search as searchListings } from '../../actions/listing-actions'
import View from './View'
class Container extends React.Component {
componentDidMount() {
if (this.props.listings.length === 0) {
this.props.searchListings();
}
}
render() {
console.log('rendering list', this.props.listings);
return (
<View listings={this.props.listings}/>
);
}
}
Container.propTypes = {
listings: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
searchListings: React.PropTypes.func.isRequired,
};
const mapStateToProps = function(store) {
return {
listings: store.listingSearch.listings
};
};
export default connect(mapStateToProps, { searchListings })(Container);
As I said I can't repro this issue now. I'll try to make some synthetic example to repro this later when I have more time.
You should load on componentDidMount() as recommended in the docu. You can also see in this example from the creator of Redux.

React Redux Confusion

Redux has proven a little tricky for me to wrap my head around, and I was wondering if someone could help point me in the right direction of what piece I am not grasping to get my desired results. Just a forewarning: I am using ES6 syntax.
Okay, so I have setup somewhat of a sandbox to test out how redux works, and this is the current file setup I am working with.
-actions
--index.js
-reducers
--index.js
--reducer_user.js
-containers
--ReduxTest.js
In my container, ReduxTest.js, I have the following code.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions/index';
class ReduxTest extends Component {
render() {
return (
<div>
{console.log(this.props.fetchUser())}
{console.log(this.props.user)}
</div>
)
}
}
export default connect( null, { fetchUser } ) (ReduxTest);
When I render ReduxTest.js to the screen, the first console.log statement shows up as,
Object { type: "FETCH_USER", payload: "This is just a test."}
The second one however, shows up as "undefined".
Here is what my actions index.js looks like,
export const FETCH_USER = 'FETCH_USER';
export function fetchUser() {
const testing = "This is just a test.";
return {
type: FETCH_USER,
payload: testing
}
}
Here is my reducer_user.js file
import { FETCH_USER } from '../actions/index';
export default function(state = null, action) {
switch(action.type) {
case FETCH_USER:
return action.payload;
}
return state;
}
and finally, here is my index.js in the reducer folder
import { combineReducers } from 'redux';
import UserReducer from './reducer_user';
const rootReducer = combineReducers({
user: UserReducer
});
export default rootReducer;
I am using a video tutorial from Udemy, so that is where I am getting some of my syntax and what not. I was under the impression that I would be able to access "this.props.user" from the index.js reducer, but I am doing something wrong, or missing a step. Any help would be appreciated.
Just so I am clear, all my intention is, is to successfully have the ReduxTest container console log JUST the string that is in the payload. if you can help with that, I think I can carry it on from there. Thanks =)
You're only passing the action creator to your component. If you want to access your props.user than you have to provide it. You can achieve this by the first argument of the connect function.
const mapStateToProps = state => ({
user: state.user,
});
export default connect(mapStateToProps, { fetchUser })(ReduxTest);
The first argument of connect must be a callable function. The only argument of this function is the current state. The function must return an object, containing all properties you want to access inside your component.
Please notice that the state of your user reducer is set to null initially. Redux fires multiple, internal actions. If you log your current state in your render method, it can happen, that your state gets logged before you are calling your own actions. This can be confusing.
You can change the initial state of your reducer this way:
import { FETCH_USER } from '../actions/index';
export default function(state = 'User not fetched yet', action) {
switch(action.type) {
case FETCH_USER:
return action.payload;
}
return state;
}

How to get dispatch redux

I'm learning redux and react. I am following some tutorials, in order to make a app.
I have this action:
export function getDueDates(){
return {
type: 'getDueDate',
todo
}
}
this is the store:
import { createStore } from 'redux';
import duedates from './reducers/duedates'
export default createStore(duedates)
This is the reducer:
import Immutable from 'immutable'
export default (state = Immutable.List(['Code More!']), action) => {
switch(action.type) {
case 'getDueDate':
return state.unshift(action.todo)
default:
return state
}
}
and in the entry point js I have this:
import React from 'react';
import ReactDOM from 'react-dom';
import store from './app/store'
import { Provider } from 'react-redux'
import App from './app/Components/AppComponent';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
Now, (according to some examples), I should call getDueDate from the dispatch but I dont get how to get the dispatch on the component, to trigger the action
Use connect from react-redux package. It has two functions as params, mapStateToProps and mapDispatchToProps, which you are interested in now. As per answer from Nick Ball, which is partially right, you will be exporting like this:
export default connect(mapStateToProps, mapDispatchToProps)(App)
and your mapDispatchToProps will look something like this:
function mapDispatchToProps (dispatch, ownProps) {
return {
getDueDate: dispatch(getDueDate(ownProps.id))
}
}
as long as your component connected to the store has property id passed from above, you'll be able to call this.props.getDueDate() from inside of it.
EDIT: There is probably no need of using an id in this case, however my point was to point out that props go as second parameter :)
The missing piece here is the connect function from react-redux. This function will "connect" your component to the store, giving it the dispatch method. There are variations on how exactly to do this, so I suggest reading the documentation, but a simple way would be something like this:
// app/Components/AppComponent.js
import { connect } from 'react-redux';
export class App extends React.Component {
/* ...you regular class stuff */
render() {
// todos are available as props here from the `mapStateToProps`
const { todos, dispatch } = this.props;
return <div> /* ... */ </div>;
}
}
function mapStateToProps(state) {
return {
todos: state.todos
};
}
// The default export is now the "connected" component
// You'll be provided the dispatch method as a prop
export default connect(mapStateToProps)(App);

Categories

Resources