React Redux : Action creator not calling reducer - javascript

My action creator is not calling my reducer. Any help will be much appreciated.
types.js
export const SELECTED_FOOD = 'selected_food';
index.js (action creator / action)
import {
SELECTED_FOOD
} from './types';
export function selectedFood({data}) {
console.log('SELECTED_FOOD **********************',data);
return({
type: SELECTED_FOOD,
payload: data
});
}
Output from console.log in action creator
Object {_id: "18240", description: "Croissants, apple", score: 0.75, fields: Object}
selected_food_reducer.js
import {
SELECTED_FOOD
} from '../actions/types';
export default function(state = [], action) {
switch(action.type) {
case SELECTED_FOOD:
console.log('Selected Food Reducer *************', state);
return action.payload ;
}
return state;
}
EDIT component failing to call dispatch.
I should have added this on my initial post, it appears there is something wrong in how dispatch is called. ESLint is flagging dispatch on line 3 for defined but never used.
import React from 'react';
import { connect } from 'react-redux';
import { dispatch } from 'react-redux';
import { selectedFood } from '../actions/index';
class TableRow extends React.Component {
render() {
const {
data
} = this.props;
console.log('PROPS TableRow', this.props);
const row = data.map((data) =>
<tr onClick={() => selectedFood({data})}>
<td key={data.description}>{data.description}</td>
<td key={data.id}>{data.fields.nutrients[0].amountPer100G}</td>
<td key={data.id}>{data.fields.nutrients[1].amountPer100G}</td>
<td key={data.id}>{data.fields.nutrients[4].amountPer100G}</td>
</tr>
);
return (
<tbody>{row}</tbody>
);
}
}
const mapStateToProps = (state) => {
return {
selectedFood: state.selectedFood
}
}
const mapDispatchToProps = (dispatch) => {
console.log('IN mapDispatchToProps')
return {
onClick: ({data}) => {
dispatch(selectedFood({data}))
}
}
}
export default connect(mapStateToProps, mapDispatchToProp)(TableRow);

The action creator does not call the reducer. It is what it is, nothing more, it creates an action - that is, an object with the action type and the payload for that action.
You need to dispatch an action, to force redux to call the reducer, and that is the place where you use your action creator, that is:
import { Dispatch } from "redux";
import { selectedFood } from "./actions";
Dispatch(selectedFood({type:"hamburger"}));
that should call the reducer, however mostly you'll not call the Dispatch directly, rather in your mapDispatchToProps method used to connect your react component to the redux store.
There are plenty of sample how to use react-redux to use above map functionality, so I would suggest to read into it, and to read how redux works.
====== EDIT after question updated =========
So firstly dispatch from import is not used and ESLint is right telling it, you don't need that import since in:
const mapDispatchToProps = (dispatch) => {
console.log('IN mapDispatchToProps')
return {
onClick: ({data}) => {
dispatch(selectedFood({data}))
}
}
}
you don't call dispatch from your import only from the argument, it's passed to your mapDispatchToProps by the connect function.
Then this is just plain wrong:
<tr onClick={() => selectedFood({data})}>
you imported an action creator which is called on click of table row, that is an action definition is created by the action creator, and that's it. Your code does exactly what you wrote.
The mapDispatchToProps function does what the name suggests - it maps dispatch functions to props of your component.
So it should be:
<tr onClick={() => this.props.onClick({data})}>
and that should dispatch the action and work.
However I would strongly suggest to take some courses or read more about react, redux and react-redux, because your code samples and the question itself suggest, that you are just trying to get something to work, without the basic understanding how it works, and even how javascript works. Sorry for that comment but that's how it looks like.

I think you might need to show how you're importing other files. My observations from what you shared:
1) You need to import SELECTED_FOOD from types.
2) Your return state should be within the context of the switch statement.

There is an often forgotten rule in Redux that when you change the reducer you need to restart your localhost server.
You are doing it correctly- there are many ways to architect Redux into React. You don't need to use mapDispatchToProps if you are importing your action creators using connect()().
Just restart your localhost server if you don't see any typos. (I usually use NPM, so I control+c out of npm start in the terminal and run npm start again each time I add a new reducer.)

Related

How to access redux-toolkit reducer/action from a class component using react-redux connect()?

I have a redux-toolkit store at store.js.
import { configureStore } from '#reduxjs/toolkit';
import productCurrency from './stateSlices/productCurrency';
const Store = configureStore({
reducer: {
productCurrency: productCurrency,
},
})
export default Store;
The createslice() function itself is in a different file and looks like this below.
import { createSlice } from '#reduxjs/toolkit'
const initialState = {
value: '$',
}
export const productCurrency = createSlice({
name: 'productCurrency',
initialState,
reducers: {
setproductCurrency(state, newState) {
state.value = newState
},
},
})
export const { setproductCurrency } = productCurrency.actions;
export default productCurrency.reducer;
My issue is that I have a class component NavSection that needs to access the initial state and the reducer action setproductCurrency() to change the state. I am trying to use the react-redux connect() function to accomplish that.
const mapStateToProps = (state) => {
const { productCurrency } = state
return { productCurrency: productCurrency.value }
}
const mapDispatchToProps = (dispatch) => {
return {
setproductCurrency: () => dispatch(setproductCurrency()),
dispatch,
}
}
export default connect(mapStateToProps, mapDispatchToProps)(NavSection);
Now, I am able to access the state by ussing this.props.productCurrency. Yet, if I try to access the setproductCurrency() by ussing this.props.setproductCurrency()... Chrome console gives me an error that "this.props.setproductCurrency() is not a function".
Is there a way of fixing this, or am I trying to do something impossible?
UPDATE #1
I think I just moved the ball in the right direction. I changed the onClick function to be an arrow function as shown below.
onClick={() => this.props.setproductCurrency('A$')}
Now, setproductCurrency() is considered a function, but it returns a different error when I click the button...
Objects are not valid as a React child (found: object with keys {type, payload}). If you meant to render a collection of children, use an array instead.
Why would this function now return an object? It is supposed to change the state and trigger a re-render of the page so that the class component can access the newly changed state.
To be clear, RTK has nothing to do with React-Redux, connect, or mapDispatch :)
The current error of "Objects are not valid as a React child" is because your reducer is wrong. A reducer's signature is not (state, newState). It's (state, action). So, your line state.value = newStateis reallystate.value = action`, and that's assigning the entire Redux action object as a value into the state. That's definitely not correct conceptually.
Instead, you need state.value = action.payload.

How to update redux state using a react variable passed up to the component from a child

Im trying to update my Redux state in a component using a variable passed up to that component from a child, following a form submital callback. The form submits a users comment, which i want to store in my redux state. I'm unsure how to send this variable into the redux chain so i can use it in my action creator. I want to pass the newComment variable inside handleCommentSubmit into the this.props.getVideoComments() action creator. Here is the code:
CommentSection.js (where i want to update my state)
//redux stuff
import {connect} from 'react-redux'
import {getVideoComments} from '../actions'
class CommentsSection extends React.Component{
constructor(props){
super(props)
//this.state={comments:[], loading:false}
}
componentDidMount(){
this.props.getVideoComments()
}
handleCommentSubmit = (newComment) =>{
// call action creator to dist action to all reducers and update relevant states
this.props.getVideoComments()
//this.setState({comments: [...this.state.comments, newComment]})
//this.setState({comments: newComments},console.log('The current state is now',this.state.comments));
//comment is object with author and message. Add new comment to old comments
//this.setState({comments:[...this.state.comments,newComment]},console.log(this.state, 'state updated'))
}
//Comments are create in comment form, passed up then sent down through commentList to individual comment rendering inside comment.js
// comment form oncommentsubmit running everytime it renders, not only on submital
render(){
const {comments} = this.props
console.log({comments})
return(
<div>
<span><h4> Comments </h4></span>
<div className="ui grid">
<div className = "right floated eight wide column" >
<CommentList comments={comments}/>
</div>
<div className="left floated eight wide column">
<CommentForm onCommentSubmit={this.handleCommentSubmit}/>
</div>
</div>
</div>
)
}
}
//redux stuff
//called following state update
const mapStateToProps = (state) => {
return {comments:state.videoComments}
}
export default connect(mapStateToProps,{getVideoComments:getVideoComments})(CommentsSection)
index.js (for action creators)
import React from 'react'
export const getVideoComments= ()=> {
return (dispatch, getState)=> {
const videoComments = getState().videoComments
return ({
type: 'GET_VIDEO_COMMENTS',
payload: videoComments
})
}
}
videoCommentsReducer.js
import React from 'react'
const videoCommentsReducer=function(state= [], action){ // reads in previous state
switch (action.type){
case 'GET_VIDEO_COMMENTS':
return action.payload //reducer will update state to be payload.videoComments. Action only describes what happened
// reducer describes how what happened effects state. Could also use previous state and action to create new data
default:
return state
}
}
export default videoCommentsReducer
index.js (in reducer folder where they are combined)
import React from 'react'
import {combineReducers} from 'redux'
import videoCommentsReducer from './videoCommentsReducer'
export default combineReducers({
videoComments:videoCommentsReducer
})
From your action creator file, it seems that you are using the redux-thunk middleware, so make sure to import this library and apply it in the store. This codesandbox shows a complete example based on yours.
When using this thunk, make sure to always use the dispatch that it provides in order to send the action to the store. Don't return an object from the bound action creator:
export const getVideoComments = () => {
return (dispatch, getState) => {
const videoComments = getRandomComments();
dispatch({
type: "GET_VIDEO_COMMENTS",
payload: videoComments
});
};
};
Also, it doesn't make sense to use getState here to get the video comments. You would simply update the store with the same state over and over again. getState is useful when you want to interact with a different part of the state, that is outside the reducer that captures your action type.
Use mapDispatchToProps in your CommentSection.js and there's no need to use getState in your action creator.
Action Creator
const getVideoComments = (comments) => ({
type: 'GET_VIDEO_COMMENTS',
payload: comments,
});
CommentSection.js
// handleCommentSubmit
handleCommentSubmit = (newComment) => {
this.props.getVideoComments(newComment); //pass comment to action then access newComment in reducer then add it to your state
}
mapDispatchToProps = (state) => {
getVideoComments: (newComment) => dispatch(getVideoComments(newComment)),
}
export default connect(mapStateToProps, mapDispatchToProps)(CommentsSection);
Reducer.js
case 'GET_VIDEO_COMMENTS':
return [...state, action.payload];
Thought id post my solution as an answer as it combined parts of both answers, but needed bits of both to fully solve the issue.
By combining parts of both the above answers I was able to fully solve the problem. I removed getState() as both fctmolina and Rodrigo Amaral suggested. I also simplified the action creator to returning a javascript object, rather than a function, and so no longer needed to include a dispatch function, or use redux-thunk. I passed the newComment variable into my action creator, and then combined it with my old state inside the reducer. The solution only required a simply definition of the mapDispatchToProps as a JS object containing the action creator getVideoComments, which made it available as a prop to commentSection, and resulted in the action creator being dispatched when the this.props.getVideoComments() function call was made. Here is the altered code:
CommentSection.js
import React from 'react'
import CommentList from './CommentList'
import CommentForm from './CommentForm'
//redux stuff
import {connect} from 'react-redux'
import {getVideoComments} from '../actions'
class CommentsSection extends React.Component{
constructor(props){
super(props)
//this.state={comments:[], loading:false}
}
componentDidMount(){
console.log(this.props.comments)
}
handleCommentSubmit = (newComment) =>{
// call action creator to dist action to all reducers and update relevant states
this.props.getVideoComments(newComment)
}
//Comments are create in comment form, passed up then sent down through commentList to individual comment rendering inside comment.js
// comment form oncommentsubmit running everytime it renders, not only on submital
render(){
const {comments} = this.props
console.log({comments})
return(
<div>
<span><h4> Comments </h4></span>
<div className="ui grid">
<div className = "right floated eight wide column" >
<CommentList comments={comments}/>
</div>
<div className="left floated eight wide column">
<CommentForm onCommentSubmit={this.handleCommentSubmit}/>
</div>
</div>
</div>
)
}
}
//redux stuff
//called following state update
const mapStateToProps = (state) => {
return {comments:state.videoComments}
}
export default connect(mapStateToProps,{getVideoComments:getVideoComments})(CommentsSection)
videoCommentsReducer.js
import React from 'react'
const videoCommentsReducer=function(state= [], action){ // reads in previous state
switch (action.type){
case 'GET_VIDEO_COMMENTS':
return [...state, action.payload] //reducer will update state to be payload.videoComments. Action only describes what happened
// reducer describes how what happened effects state. Could also use previous state and action to create new data
default:
return state
}
}
export default videoCommentsReducer
index.js (for action creator)
import React from 'react'
export const getVideoComments = (newComment) => {
return({
type: 'GET_VIDEO_COMMENTS',
payload: newComment
})
};

redux async with redux thunk doesn't work with #connect

I try to use setTimeout as a mock for rest api, but my redux seems has flawed.
https://codesandbox.io/s/1zr78rp48j
partial code
#connect(state => state.items, { approveItem })
export default class Items extends Component {
render() {
return (
<div>
<div>status: {this.props.item.status}</div>
<button onClick={() => approveItem()}>{this.props.loading ? 'loading...' : 'Approve'}</button>
</div>
);
}
}
I wonder why this simple flow won't work, is my setTimeout function in the reducer make sense? I'm using redux-thunk.
i have corrected your code , take a look
https://codesandbox.io/s/14j6m2661q
the issue was in your class
export class Items extends Component {
render() {
console.log(approveItem);
return (
<div>
<div>status: {this.props.items && this.props.items.item.status}</div>
<button onClick={() => this.props.approveItem()}>Approve </button>
</div>
);
}
}
// start of code change
const mapStateToProps = (state) => {
return { items: state.items };
};
const mapDispatchToProps = (dispatch) => {
return {
approveItem: () => dispatch(approveItem())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Items);
If you want redux to take the action creators and wrap them in a function that will dispatch their result you have to pass an object with the action creators as it's members to mapDispatchToProps (you are doing this correctly).
But in the component you are not using the wrapped action creator, you are using the imported approveItem The correct code to create auto dispatched action creators is:
import React, { Component } from "react";
import { connect } from "react-redux";
import { approveItem } from "./actions";
//mapDispatchToProps is an object here, all function members of the object
// will be treated as action creators and wrapped in a function that when
// called will automatically dispatch their result
const mapDispatchToProps = { approveItem };
#connect(state => state.items, mapDispatchToProps)
export default class Items extends Component {
render() {
//use the wrapped action creator found on this.props
console.log(this.props.approveItem);
return (
<div>
<div>status: {this.props.item.status}</div>
<button onClick={() => this.props.approveItem()}>Approve </button>
</div>
);
}
}
You can manually wrap action creators in a function that will dispatch their results (actions). By passing a function to mapDispatchToProps.
This is is usually the case when you want to isolate components and not dump all reducers and actions on one pile. The application will wrap actions in {type:"ITEM",action:actualItemComponentAction}. Since the component doesn't know how to wrap it's actions in a action handled by application the application needs to pass wrappers to action creators that return functions for thunk and wrap actual action objects with a type that can be handled by the application reducer.
Not sure how bindActionCreators fits into this because if you manually want to bind action creators to components you usually don't want to auto bind them but rather want to wrap the component action in a application action.
An example work in progress can be found here.

How to update state using Redux?

I am using this starter kit https://github.com/davezuko/react-redux-starter-kit and am following some tutorials at the same time, but the style of this codebase is slightly more advanced/different than the tutorials I am watching. I am just a little lost with one thing.
HomeView.js - This is just a view that is used in the router, there are higher level components like Root elsewhere I don't think I need to share that, if I do let me know, but it's all in the github link provided above.
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { searchListing } from '../../redux/modules/search'
export class HomeView extends React.Component {
componentDidMount () {
console.log(this.props)
}
render () {
return (
<main onClick={this.props.searchListing}>
<NavBar search={this.props.search} />
<Hero/>
<FilterBar/>
<Listings/>
<Footer/>
</main>
)
}
}
I am using connect() and passing in mapStateToProps to tell the HomeView component about the state. I am also telling it about my searchListing function that is an action which returns a type and payload.
export const searchListing = (value) => {
console.log(value)
return {
type: SEARCH_LISTINGS,
payload: value
}
}
Obviously when I call the method inside the connect() I am passing in an empty object searchListing: () => searchListing({})
const mapStateToProps = (state) => {
return {
search: { city: state.search }
}
}
export default connect((mapStateToProps), { searchListing: () => searchListing({}) })(HomeView)
This is where I am stuck, I am trying to take the pattern from the repo, which they just pass 1, I think anytime that action is created the logic is just add 1 there is no new information passed from the component.
What I am trying to accomplish is input search into a form and from the component pass the users query into the action payload, then the reducer, then update the new state with the query. I hope that is the right idea.
So if in the example the value of 1 is hardcoded and passed into the connect() method, how can I make it so that I am updating value from the component dynamically? Is this even the right thinking?
You almost got it right. Just modify the connect function to pass the action you want to call directly:
const mapStateToProps = (state) => ({
search: { city: state.search }
});
export default connect((mapStateToProps), {
searchListing
})(HomeView);
Then you may use this action with this.props.searchListing(stringToSearch) where stringToSearch is a variable containing the input value.
Notice : You don't seem to currently retrieve the user query. You may need to retrieve it first and then pass it to the searchListing action.
If you need to call a function method, use dispatch.
import { searchListing } from '../../redux/modules/search';
const mapDispatchToProps = (dispatch) => ({
searchListing: () => {
dispatch(searchListing());
}
});
export default connect(mapStateToProps, mapDispatchToProps)(HomeView);
Then, you have made the function a prop, use it with searchListing.

Accessing Redux state in an action creator?

Say I have the following:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
}
}
And in that action creator, I want to access the global store state (all reducers). Is it better to do this:
import store from '../store';
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
items: store.getState().otherReducer.items,
}
}
or this:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return (dispatch, getState) => {
const {items} = getState().otherReducer;
dispatch(anotherAction(items));
}
}
There are differing opinions on whether accessing state in action creators is a good idea:
Redux creator Dan Abramov feels that it should be limited: "The few use cases where I think it’s acceptable is for checking cached data before you make a request, or for checking whether you are authenticated (in other words, doing a conditional dispatch). I think that passing data such as state.something.items in an action creator is definitely an anti-pattern and is discouraged because it obscured the change history: if there is a bug and items are incorrect, it is hard to trace where those incorrect values come from because they are already part of the action, rather than directly computed by a reducer in response to an action. So do this with care."
Current Redux maintainer Mark Erikson says it's fine and even encouraged to use getState in thunks - that's why it exists. He discusses the pros and cons of accessing state in action creators in his blog post Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability.
If you find that you need this, both approaches you suggested are fine. The first approach does not require any middleware:
import store from '../store';
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
items: store.getState().otherReducer.items,
}
}
However you can see that it relies on store being a singleton exported from some module. We don’t recommend that because it makes it much harder to add server rendering to your app because in most cases on the server you’ll want to have a separate store per request. So while technically this approach works, we don’t recommend exporting a store from a module.
This is why we recommend the second approach:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return (dispatch, getState) => {
const {items} = getState().otherReducer;
dispatch(anotherAction(items));
}
}
It would require you to use Redux Thunk middleware but it works fine both on the client and on the server. You can read more about Redux Thunk and why it’s necessary in this case here.
Ideally, your actions should not be “fat” and should contain as little information as possible, but you should feel free to do what works best for you in your own application. The Redux FAQ has information on splitting logic between action creators and reducers and times when it may be useful to use getState in an action creator.
When your scenario is simple you can use
import store from '../store';
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
items: store.getState().otherReducer.items,
}
}
But sometimes your action creator need to trigger multi actions
for example async request so you need
REQUEST_LOAD REQUEST_LOAD_SUCCESS REQUEST_LOAD_FAIL actions
export const [REQUEST_LOAD, REQUEST_LOAD_SUCCESS, REQUEST_LOAD_FAIL] = [`REQUEST_LOAD`
`REQUEST_LOAD_SUCCESS`
`REQUEST_LOAD_FAIL`
]
export function someAction() {
return (dispatch, getState) => {
const {
items
} = getState().otherReducer;
dispatch({
type: REQUEST_LOAD,
loading: true
});
$.ajax('url', {
success: (data) => {
dispatch({
type: REQUEST_LOAD_SUCCESS,
loading: false,
data: data
});
},
error: (error) => {
dispatch({
type: REQUEST_LOAD_FAIL,
loading: false,
error: error
});
}
})
}
}
Note: you need redux-thunk to return function in action creator
I agree with #Bloomca. Passing the value needed from the store into the dispatch function as an argument seems simpler than exporting the store. I made an example here:
import React from "react";
import {connect} from "react-redux";
import * as actions from '../actions';
class App extends React.Component {
handleClick(){
const data = this.props.someStateObject.data;
this.props.someDispatchFunction(data);
}
render(){
return (
<div>
<div onClick={ this.handleClick.bind(this)}>Click Me!</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return { someStateObject: state.someStateObject };
};
const mapDispatchToProps = (dispatch) => {
return {
someDispatchFunction:(data) => { dispatch(actions.someDispatchFunction(data))},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
I would like to point out that it is not that bad to read from the store -- it might be just much more convenient to decide what should be done based on the store, than to pass everything to the component and then as a parameter of a function. I agree with Dan completely, that it is much better not to use store as a singletone, unless you are 100% sure that you will use only for client-side rendering (otherwise hard to trace bugs might appear).
I have created a library recently to deal with verbosity of redux, and I think it is a good idea to put everything in the middleware, so you have everyhing as a dependency injection.
So, your example will look like that:
import { createSyncTile } from 'redux-tiles';
const someTile = createSyncTile({
type: ['some', 'tile'],
fn: ({ params, selectors, getState }) => {
return {
data: params.data,
items: selectors.another.tile(getState())
};
},
});
However, as you can see, we don't really modify data here, so there is a good chance that we can just use this selector in other place to combine it somewhere else.
Presenting an alternative way of solving this. This may be better or worse than Dan's solution, depending on your application.
You can get the state from the reducers into the actions by splitting the action in 2 separate functions: first ask for the data, second act on the data. You can do that by using redux-loop.
First 'kindly ask for the data'
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
}
}
In the reducer, intercept the ask and provide the data to the second stage action by using redux-loop.
import { loop, Cmd } from 'redux-loop';
const initialState = { data: '' }
export default (state=initialState, action) => {
switch(action.type) {
case SOME_ACTION: {
return loop(state, Cmd.action(anotherAction(state.data))
}
}
}
With the data in hand, do whatever you initially wanted
export const ANOTHER_ACTION = 'ANOTHER_ACTION';
export function anotherAction(data) {
return {
type: ANOTHER_ACTION,
payload: data,
}
}
Hope this helps someone.
I know I'm late to the party here, but I came here for opinions on my own desire to use state in actions, and then formed my own, when I realized what I think is the correct behavior.
This is where a selector makes the most sense to me. Your component that issues this request should be told wether it's time to issue it through selection.
export const SOME_ACTION = 'SOME_ACTION';
export function someAction(items) {
return (dispatch) => {
dispatch(anotherAction(items));
}
}
It might feel like leaking abstractions, but your component clearly needs to send a message and the message payload should contain pertinent state. Unfortunately your question doesn't have a concrete example because we could work through a 'better model' of selectors and actions that way.
I would like to suggest yet another alternative that I find the cleanest, but it requires react-redux or something simular - also I'm using a few other fancy features along the way:
// actions.js
export const someAction = (items) => ({
type: 'SOME_ACTION',
payload: {items},
});
// Component.jsx
import {connect} from "react-redux";
const Component = ({boundSomeAction}) => (<div
onClick={boundSomeAction}
/>);
const mapState = ({otherReducer: {items}}) => ({
items,
});
const mapDispatch = (dispatch) => bindActionCreators({
someAction,
}, dispatch);
const mergeProps = (mappedState, mappedDispatches) => {
// you can only use what gets returned here, so you dont have access to `items` and
// `someAction` anymore
return {
boundSomeAction: () => mappedDispatches.someAction(mappedState.items),
}
});
export const ConnectedComponent = connect(mapState, mapDispatch, mergeProps)(Component);
// (with other mapped state or dispatches) Component.jsx
import {connect} from "react-redux";
const Component = ({boundSomeAction, otherAction, otherMappedState}) => (<div
onClick={boundSomeAction}
onSomeOtherEvent={otherAction}
>
{JSON.stringify(otherMappedState)}
</div>);
const mapState = ({otherReducer: {items}, otherMappedState}) => ({
items,
otherMappedState,
});
const mapDispatch = (dispatch) => bindActionCreators({
someAction,
otherAction,
}, dispatch);
const mergeProps = (mappedState, mappedDispatches) => {
const {items, ...remainingMappedState} = mappedState;
const {someAction, ...remainingMappedDispatch} = mappedDispatch;
// you can only use what gets returned here, so you dont have access to `items` and
// `someAction` anymore
return {
boundSomeAction: () => someAction(items),
...remainingMappedState,
...remainingMappedDispatch,
}
});
export const ConnectedComponent = connect(mapState, mapDispatch, mergeProps)(Component);
If you want to reuse this you'll have to extract the specific mapState, mapDispatch and mergeProps into functions to reuse elsewhere, but this makes dependencies perfectly clear.
I wouldn't access state in the Action Creator. I would use mapStateToProps() and import the entire state object and import a combinedReducer file (or import * from './reducers';) in the component the Action Creator is eventually going to. Then use destructuring in the component to use whatever you need from the state prop. If the Action Creator is passing the state onto a Reducer for the given TYPE, you don't need to mention state because the reducer has access to everything that is currently set in state. Your example is not updating anything. I would only use the Action Creator to pass along state from its parameters.
In the reducer do something like:
const state = this.state;
const apple = this.state.apples;
If you need to perform an action on state for the TYPE you are referencing, please do it in the reducer.
Please correct me if I'm wrong!!!

Categories

Resources