React-redux connect() not subscribing to dispatched actions properly - reactjs

I have a simple component I'm trying to make work with redux. I map both props and dispatch actions, however only the props I initially get from the store work properly. I traced it all down to my actions: they are being dispatched, but respective reducers don't really do anything. Pretty simple stuff I came up with according to the tutorial and everything looks good to me, but I can't wrap my head around the problem here.
Here is a simplified version of the app:
// index.js
import React from 'react'
import ReactDOM from 'react-dom'
import Search from './Search'
import { Provider } from 'react-redux'
import store from './store'
const root = document.querySelector('#app')
ReactDOM.render(
<Provider store={store}>
<Search/>
</Provider>, root)
// Search.js
import React from 'react'
import { setText } from '../../actions/appActions'
import { connect } from 'react-redux';
const mapStateToProps = state => {
return {
text: state.app.searchText
}
}
const mapDispatchToProps = dispatch => {
return {
setText,
dispatch
}
}
class Search extends React.Component {
constructor() {
super()
}
render() {
return (
<input type="text" onChange={() => this.props.setText("text")} value={this.props.text}/>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Search)
// store.js
import { createStore, combineReducers } from 'redux'
import app from './reducers/appReducer'
export default createStore(combineReducers({/*other non-relevant reducers*/, app}))
// appActions.js
export function setText(text) {
return {
type: "APP_SET_TEXT",
payload: text,
}
}
// appReducer.js
const initialState = {
isSearchActive: true,
searchText: "Text",
}
export default function reducer(state = initialState, action) {
switch (action.type) {
case "APP_SET_TEXT":
console.log("fart")
return {
...state,
searchText: action.payload,
}
default:
return state
}
}
What I'm trying to to is to simply make the input value change according to the redux state. I do get the text from {this.props.text}, the change handler onChange={() => this.props.setText("text")} is being dispatched, but the reducer for some reason fails to catch the action that was dispatched.

I think you should change the mapDispatchToProps variable like the following:
const mapDispatchToProps = dispatch => {
return {
setText = (text) => dispatch(setText(text)),
}
}

There are two ways to achieve this
// MODIFYING DISPATHCER
const mapDispatchToProps = dispatch => {
return {
changeText: data => dispatch(setText(data)),
}
}
or
// CONNECT
export default connect(mapStateToProps, {
setText
})(Search)

const mapDispatchToProps = dispatch => {
return {
setText,
dispatch
}
}
change to
const mapDispatchToProps = dispatch => {
return {
changeText: text => dispatch(setText(text)),
}
}
And in your component use this.props.changeText function

as most of the answers suggests you can dispatch the actions or else you can simply have mapDispatchToProps an object.
mapDispatchToProps = {
setText,
dispatch
}
Your HOC connect should take care of dispatching not need to external definition

Use bindActionCreators from redux
import { bindActionCreators } from 'redux';
const mapDispatchToProps = dispatch => {
const setText = bindActionCreators(setText, dispatch);
return setText;
}

Since you're mapping your dispatch to props like this:
const mapDispatchToProps = dispatch => {
return {
setText,
dispatch
}
}
You'll need to explicitly call dispatch in your component:
class Search extends React.Component {
constructor() {
super()
}
render() {
const {dispatch, setText} = this.props;
return (
<input type="text" onChange={() => dispatch(setText("text"))} value={this.props.text}/>
)
}
}
It is easier just to map dispatch to props like this: setText = (text) => dispatch(setText(text))

Related

How can I access my dispatch routines from my props using TypeScript + Redux?

Take a look at the following slice I've created in TypeScript (storeSlice.ts):
import { createSlice, PayloadAction } from "#reduxjs/toolkit";
import axios from "axios";
import { AppThunk } from "../../app/store";
import { Summoner } from "../../models/Summoner";
export interface StoreState {
summoners: Summoner[]
}
const initialState: StoreState = {
summoners: []
}
export const storeSlice = createSlice({
name: 'store',
initialState,
reducers: {
getSummonersSuccess: (state: StoreState, action: PayloadAction<Summoner[]>) => {
state.summoners = action.payload;
}
}
});
export const { getSummonersSuccess } = storeSlice.actions;
export const getSummoners = (): AppThunk => (dispatch) => {
axios.get("api/summoners").then((response) => {
dispatch(getSummonersSuccess(response.data));
});
}
export default storeSlice.reducer;
It's pretty basic. It has an initial state that is of type StoreState which contains an array of type Summoner.
Now, the component that uses this slice looks like this (Store.tsx):
import React, { Dispatch } from 'react';
import { connect } from 'react-redux';
import { getSummoners, StoreState } from './storeSlice';
interface PropState {
store: StoreState
}
const Store = (props: StoreState) => {
console.log("store props", props); //This contains my "getSummoners" action, but I can't access it because it's not defined in "StoreState"
return (
<h1>Hello!</h1>
);
}
const mapStateToProps = (state: PropState) => {
console.log("Store state", state);
return { summoners: state.store.summoners };
};
const mapDispatchToProps = (dispatch: Dispatch<any>) => {
return {
getSummoners: dispatch(getSummoners)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Store);
When I log the props in the component, I get the state that I've mapped with mapStateToProps, and I also get the getSummoners action that I've mapped with mapDispatchToProps.
However, I cannot actually access the getSummoners action because it is not defined in StoreState.
I do not want to have to define the actions in every default state type that I create.
Is there something I can do to be able to use the dispatch actions in my code whilst keeping TypeScript happy?
Apologies if this question doesn't make too much sense, I'm fairly new to this tech stack.
In your mapDispatchToProps you are inadvertanly calling the dispatch rather than returning a function to call the dispatch from your component. Change it to:
const mapDispatchToProps = (dispatch: Dispatch<any>) => {
return {
getSummoners: () => dispatch(getSummoners)
}
}
This should clear up your problems. If it doesn't, please update your post with the exact error that you are getting.
As a sidenote, this connect higher-order component with mapStateToProps and mapDispatchToProps has been around for a while and it used to be the only way to get data from the state into your component. It still works, but nowadays it is recommended that you use the newer hooks useSelector and useDispatch instead.

React-Redux: Using action creators in React components

I am new to React/Redux, and appreciate your help. I am taking a Udemy course on this topic. The course instructor creates a component like this.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions';
class User extends Component {
componentDidMount(){
this.props.fetchUser(this.props.userId);
}
render(){
const { user } = this.props;
if(!user) return null;
return(
<div className="header"> User Info: {user.name}</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return { user: state.users.find( user => user.id === ownProps.userId)};
};
export default connect(mapStateToProps, { fetchUser })(User)
my question: why inside the componentDidMount() he is prefixing fetchUsers() with this.props?
it is not the case that he is passing fetchUsers() as props from the parent component. This is how the parent is using this component <User userId={post.userId}/>
Note: this code works
It is because of this line :
export default connect(mapStateToProps, { fetchUser })(User)
the second parameter to connect is called mapDispatchToProps, It adds the actions to props
From the docs :
connect can accept an argument called mapDispatchToProps, which lets
you create functions that dispatch when called, and pass those
functions as props to your component.
const mapDispatchToProps = dispatch => {
return {
// dispatching plain actions
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' }),
reset: () => dispatch({ type: 'RESET' })
}
}
Your code is using the “object shorthand” form.
The way the mapDispatchToProps in the example is shorthanded. It might be easier to tell what is going if it was written like so:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions';
class User extends Component {
componentDidMount(){
this.props.fetchUser(this.props.userId);
}
render(){
const { user } = this.props;
if(!user) return null;
return(
<div className="header"> User Info: {user.name}</div>
);
}
}
const mapStateToProps = (state, ownProps) => {
return { user: state.users.find( user => user.id === ownProps.userId)};
};
const mapDispatchToProps = () => ({
fetchUser
});
export default connect(mapStateToProps, mapDispatchToProps)(User)
Maybe this shows it more clearly, but the dispatch function (fetchUser) is being mapped to the components properties. Just like the state value (user) is being mapped to the properties of the component. I think you just got confused because of the shorthand that was used.

How to access redux-store from within react's componentDIdMount()

In the following code I am trying to pass the state.userData.userDetails from the redux-store to getleftpaneProductCatalogue(), but state.userData.userDetails is unaccessible to componentDidMount(). I tried assigning the state.userData.userDetails to this.prop.userProfile, but still this.prop.userProfile is an empty value. How to access the prop within componentDidMount?
import React,{Component} from 'react';
import { connect } from 'react-redux';
import {Row, Col } from 'react-materialize';
import {getleftpaneProductCatalogue} from '../actions/leftpane-actions';
import ProductCatalogueLeftPaneComp from '../components/pages/product-catalogue-leftpane';
class ProductCatalogueLeftPane extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
console.log('this.props^', JSON.stringify(this.props));
this.props.getleftpaneProductCatalogue().then((data) => {
console.log('productdata', data);
})
}
render() {
return (
<div>
{JSON.stringify(this.props.userProfile)}
</div>
)
}
}
const mapStateToProps = (state) => {
console.log('state^', JSON.stringify(state));
return {leftpaneProductCatalogue: state.leftpaneProductCatalogue, userProfile: state.userData.userDetails};
};
const mapDispatchToProps = (dispatch) => {
return {
getleftpaneProductCatalogue: () => dispatch(getleftpaneProductCatalogue()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(ProductCatalogueLeftPane);
You can access the state directly in mapDispatchToProps and pass it to getleftpaneProductCatalogue:
componentDidMount() {
const { dispatch, getleftpaneProductCatalogue }
dispatch(getleftpaneProductCatalogue())
}
const mapDispatchToProps = dispatch => {
return {
getleftpaneProductCatalogue: () => (dispatch, getState) => {
const state = getState()
const details = state.userData.userDetails
return dispatch(getleftpaneProductCatalogue(details))
},
dispatch
}
}
However, the way you're doing it, passing the state via mapStateToProps is still valid, but more verbose. Therefore the problem would be somewhere else.
Here's my bet. I guess you're getting the userData somewhere in your code with async API call and it's not being fetched yet. If that's the case - then you should wait for data being fetched firstly, then you can access it in your component ProductCatalogueLeftPane.

Error: Actions must be plain objects. Use custom middleware for async actions.- Even the actions contain the method

i am new to react , just understanding the concept on redux without using redux thunk. please see the below code
// app.js
import React, { Component } from 'react';
import {connect} from 'react-redux';
import * as actions from './actions'
class App extends Component {
render() {
return (
<div>
<button onClick={this.props.fetchData}>Show Data</button>
</div>
);
}
}
const mapStateToProps = state => {
return {
}
}
const mapDispatchToProps = dispatch => {
return {
fetchData: () => dispatch(actions.fetchDataHandler)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import {createStore} from 'redux';
import Data from './reducers';
import {Provider} from 'react-redux';
const store = createStore(Data)
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
registerServiceWorker();
//actions-index.js
export const fetchDataHandler = e => dispatch => {
console.log("hit here");
}
//reducers-index.js
// default state
const defaultState = {
data: null
}
let data;
export default data = (state=defaultState, action) => {
switch(action.type){
case "FETCH_DATA":
return {
...state,
data: action.payload
}
default:
return{
...state
}
}
}
folder structure is
src
actions
index.js
reducers
index.js
app.js
i am not using redux thunk, when the button is clicked it will call the fetchData which will invoke the actions.fetchDataHandler
so on the console it should get a message as "hit here", but its not working.
sorry if i am not understanding the redux concept properly.
In a normal redux flow, Actions are supposed to be plain object, i.e an action creator must return a plain object, But in your case since you haven't need using any middleware like redux-thunk, you can not write an action like
//actions-index.js
export const fetchDataHandler = e => dispatch => {
console.log("hit here");
}
A general way to do it would be
export const fetchDataHandler = e => {
console.log("hit here");
return {
type: 'MY_ACTION'
}
}
However if you configure a middleware like redux-thunk, you can have an asynchronous action within your action creators like
//actions-index.js
export const fetchDataHandler = e => dispatch => {
console.log("hit here");
API.call().then((res) => {
dispatch({ type: 'API_SUCCESS', payload: res });
});
}
Also your mapDispatchToProps isn't calling the action in dispatch, you would either write it like
const mapDispatchToProps = dispatch => {
return {
fetchData: () => dispatch(actions.fetchDataHandler())
}
}
or
const mapDispatchToProps = {
fetchData: actions.fetchDataHandler
}

React Redux - How to dispatch an action on componentDidMount when using mapDispatchToProps in a connected component

I'm having problems with this. I'm creating a small app with react redux.
In the code below is my app.js component. It was working fine until I tried to use the mapDispatchToProps function inside connect. The problem is that I cannot invoke the dispatch action on componentDidMount anymore. The actions that were in componentDidMount and that now are on mapStateToProps need to be called on comoponentDidMount. Any clues in how to do that?
import React, { Component } from 'react';
import './App.css';
import '../../node_modules/bootstrap/less/bootstrap.less';
import { Route } from 'react-router-dom'
import * as ReadableAPI from '../ReadableAPI'
import HeaderNavigation from './HeaderNavigation';
import TableBody from './TableBody';
import { connect } from 'react-redux';
import sortAsc from 'sort-asc';
import sortDesc from 'sort-desc';
import {
selectedCategory,
fetchCategoriesIfNeeded,
fetchPostsIfNeeded,
invalidateSubreddit,
orderPost
} from '../actions'
class App extends Component {
state = {
posts: []
}
componentDidMount() {
const { dispatch, selectedCategory, fetchCategories, fetchPosts} = this.props
//dispatch(fetchCategoriesIfNeeded(selectedCategory))
//dispatch(fetchPostsIfNeeded(selectedCategory))
}
orderByScoreAsc = (posts) => {
return posts.sort(sortAsc('voteScore'))
}
orderByScoreDesc = (posts) => {
return posts.sort(sortDesc('voteScore'))
}
render() {
const { navCategories, posts } = this.props
return (
<div>
<HeaderNavigation navCategories = {navCategories} />
<Route exact path="/" render={()=>(
<TableBody
showingPosts={posts}
/>)}
/>
</div>
);
}
}
function mapStateToProps ( state ) {
const { categories, posts } = state
return {
navCategories: categories.items,
posts: posts.items
}
}
function mapDispatchToProps (dispatch) {
return {
changeOrder: (data) => dispatch(orderPost(data)),
fetchCategories: (data) => dispatch(fetchCategoriesIfNeeded(data)),
fetchPosts: (data) => dispatch(fetchPostsIfNeeded(data))
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App)
I modified your code to what I think will work. I also left comments.
class App extends Component {
state = {
posts: []
}
componentDidMount() {
// no need to use dispatch again. Your action creators are already bound by
// mapDispatchToProps. Notice also that they come from props
const { selectedCategory, fetchCategoriesIfNeeded, fetchPostsIfNeeded} = this.props;
fetchCategoriesIfNeeded(selectedCategory);
fetchPostsIfNeeded(selectedCategory);
}
//... the same
}
function mapStateToProps ( state ) {
//... the same
}
function mapDispatchToProps (dispatch) {
// when arguments match, you can pass configuration object, which will
// wrap your actions creators with dispatch automatically.
return {
orderPost,
fetchCategoriesIfNeeded,
fetchPostsIfNeeded,
}
}
In map to dispatch you have fetchCategories/fetchPosts so therefore you need to call them like this:
componentDidMount() {
const { dispatch, selectedCategory, fetchCategories, fetchPosts } = this.props
//Call like this instead of fetchCategoriesIfNeeded/fetchPostsIfneeded
//dispatch(fetchCategories(selectedCategory))
//dispatch(fetchPosts(selectedCategory))
}
You have this:
function mapDispatchToProps (dispatch) {
return {
changeOrder: (data) => dispatch(orderPost(data)),
fetchCategories: (data) => dispatch(fetchCategoriesIfNeeded(data)),
fetchPosts: (data) => dispatch(fetchPostsIfNeeded(data))
}
}
So you need to call fetchCategories/fetchPosts from your props instead of fetchCatIfneeded/fetchPostsifneeded
You just don't. The mapDispatchToProps does exactly what you are trying to do in your component. Instead of calling a dispatch you call the method that was provided to your component by connect. in your case:
componentDidMount() {
const { selectedCategory, fetchCategories, fetchPosts} = this.props;
fetchCategories(selectedCategory);
fetchPosts(selectedCategory);
}

Resources