Uncaught error: dispatch is not a function - reactjs

I am using redux-saga along with reactjs. I am using mapDispatchToProps to trigger onClick changes with values but I am getting above error saying that dispatch is not defined anyone please let me know how to resolve this in saga way?
import { connect } from 'react-redux';
import { updateModifiedValue } from "../actions/programActions";
import { bindActionCreators } from 'redux';
export class ProgramProfileContainer extends React.Component {
render() {
return (
<div>
<ProgramVolumeComponent
updateModifiedGrowth = {(value) => updateModifiedValue(value,this.props.match.params.program_id)}
/>
</div>
)
}
}
const mapStateToProps = (state) => {
console.log("update state", state)
return {
programProfileData: state.programDetailReducer.programDetails,
}
}
const mapDispatchToProps= (dispatch) => (
bindActionCreators({updateModifiedValue},dispatch)
)
export default connect(
mapStateToProps,
mapDispatchToProps)(ProgramProfileContainer)
this is my action
export function updateModifiedValue(Value,Id){
console.log("mval",Value)
console.log("id",Id)
return {
type:types.MODIFIED_GROWTH,
growthValue
}
}
here is my index saga
export default function* startForman() {
console.log("index saga")
yield fork(watcher);
}
watcher
export default function* watcher(){
yield takeLatest(types.LISTS,myCallSaaga)
}
and my calll saaga
export default function* myCallSaaga({Value,Id}){
const array=[Value,Id]
try {
const Data = yield call(growthdetail,...array)
yield [
put({ type: types.MODIFIED, Detail: Data })
]
} catch (error) {
yield put({
type: 'FETCH_ERROR',
error
});
}
}
and my reducer
export default function(state=[],action){
switch(action.type){
case types.PRO_LIST:
return [...state,action.List]
case types.MODIFIED:
return {...state,growth:4}
default:
return state
}
}

I think the error is that you are calling the action directly from your import and not from your props, which is what mapDispatchToProps is for. Try this:
import programActionsCreator from "../actions/programActions";
...
render() {
const { updateModifiedValue } = this.props.actions;
return() {
...
updateModifiedGrowth = {(value) => updateModifiedValue(value, this.props.match.params.program_id)}
...
}
...
const mapDispatchToProps= (dispatch) => ({
actions: bindActionCreators(programActionsCreator, dispatch)
})

from rowland's comment and from this github post I made the changes like this
const mapDispatchToProps= (dispatch) => {
return { dispatch,
...bindActionCreators({
updateModifiedValue
}, dispatch)}//bindActionCreators({updateModifiedValue},dispatch)
}
and
<ProgramVolumeComponent
updateModifiedGrowth = {(value) => this.props.updateModifiedValue(value,this.props.match.params.program_id)}
/>
basically we need to pass our own dispatch we are mapDispatchToProps

Related

Err Call Api on redux observable using Axios

I'm trying to learn redux-observables but I seem to be having an issue getting my app to return data. I keep getting the error below and I'm not sure where I'm going wrong or what the error actually means.
I'm trying to learn redux-observables but I seem to be having an issue getting my app to return data. I keep getting the error below and I'm not sure where I'm going wrong or what the error actually means.
I'm trying to learn redux-observables but I seem to be having an issue getting my app to return data. I keep getting the error below and I'm not sure where I'm going wrong or what the error actually means.
I'm trying to learn redux-observables but I seem to be having an issue getting my app to return data. I keep getting the error below and I'm not sure where I'm going wrong or what the error actually means.
ERR: fetchData is not a function
I need help
Contsants
export const FETCH_DATA = "FETCH_DATA";
export const FETCH_DATA_FAIL = "FETCH_DATA_FAIL ";
Action
import { FETCH_DATA, FETCH_DATA_FAIL } from "../contsants/contsants";
export const fetchData = (exampleData = {}) => ({
type: FETCH_DATA,
payload: exampleData
});
export const fetchDataFail = () => ({
type: FETCH_DATA_FAIL
});
Store
import { createStore } from "redux";
import rootReducer from "../Reducer/reducer";
const store = createStore(rootReducer);
export default store;
Reducer
import { FETCH_DATA, FETCH_DATA_FAIL } from "../contsants/contsants";
import { combineReducers } from "redux";
const initialState = {};
export const exampleData = (state = initialState, action: any) => {
switch (action.type) {
case FETCH_DATA:
return action.payload;
case FETCH_DATA_FAIL:
return {};
default:
return state;
}
};
export default combineReducers({
exampleData
});
Epics
import "rxjs";
import axios from "axios";
import { from, of } from "rxjs";
import { mergeMap, map, catchError } from "rxjs/operators";
import { ofType } from "redux-observable";
import { FETCH_DATA } from "../contsants/contsants";
import { fetchData, fetchDataFail } from "../Actions/action"
export const exampleEpic = (action$: any) =>
action$.pipe(
ofType(FETCH_DATA),
mergeMap((action) =>
from(axios.get("jsonplaceholder.typicode.com/todos/1")).pipe(
map((response) => fetchData(response.data)),
catchError(() => of(fetchDataFail()))
)
)
);
App
import { fetchData } from './Actions/action'
import { connect } from "react-redux";
function App(data: any, fetchData: any) {
const handleClickShowsTodos = () => {
fetchData()
console.log(data);
}
return (
<div>
<input type="text" />
<button onClick={handleClickShowsTodos}>ShowsTodo</button>
</div>
);
}
const mapStateToProps = (state: any) => {
return {
data: state
};
};
function mapDispatchToProps(dispatch: any) {
return {
fetchData: () => {
console.log('dispatch')
dispatch(fetchData())
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);

this.props.dispatch is not a function. Not able to dispatch mapdispatchtoprops

I've been trying to dispatch a function that will call an async parse cloud function. It worked well in my other projects when i used them in functions. But this is the first time i'm using them in a component and when i call the dispatch from map dispatch to props, I get this error. Please help me out.
ProfileHeader.js
import React, { Component } from 'react';
import Cover_Image from './Cover_Image.jpg';
import Profile_Pic from './Profile_Pic.svg';
import './ProfileHeader.css';
import { connect } from 'react-redux';
import { fetchUserProfile } from '../../Redux/UserProfile-Redux/UserProfileActionMethods';
class ProfileHeader extends Component {
componentDidMount() {
this.props.fetchUserProfile()
}
render() {
return (
<div className="profile-header-layout"></div>
)
}
}
const mapStatetoProps = (state) => {
return {
profile: state.UserProfile
}
}
const mapDispatchtoProps = (dispatch) => {
return {
fetchUserProfile: () => { dispatch(fetchUserProfile()) }, dispatch,
}
}
export default connect(mapDispatchtoProps, mapStatetoProps)(ProfileHeader)
The action Method:
import Parse from 'parse/dist/parse.min.js';
import { FETCH_USERPROFILE_FAILURE, FETCH_USERPROFILE_REQUEST, FETCH_USERPROFILE_SUCCESS } from './UserProfileActions';
const params = { username: "prvnngrj" }
export const fetchUserProfileRequest = () => {
return {
type: FETCH_USERPROFILE_REQUEST
}
}
export const fetchUserProfileSuccess = (userprofiles) => {
return {
type: FETCH_USERPROFILE_SUCCESS,
payload: userprofiles
}
}
export const fetchUserProfileFailure = (error) => {
return {
type: FETCH_USERPROFILE_FAILURE,
payload: error
}
}
export const fetchUserProfile = () => {
return async dispatch => {
dispatch(fetchUserProfileRequest)
try {
const responsedata = await Parse.Cloud.run("GetUserProfileForUsername", params);
const userprofiles = responsedata;
dispatch(fetchUserProfileSuccess(userprofiles))
}
catch (error) {
const errorMessage = error.message
dispatch(fetchUserProfileFailure(errorMessage))
}
}
}
Please ignore parts of code which do not make it relevant, its straight from the project
You mixed up the order of your arguments, so this.props.dispatch is actually your state!
You need to change
export default connect(mapDispatchtoProps, mapStatetoProps)(ProfileHeader)
to:
export default connect(mapStatetoProps, mapDispatchtoProps)(ProfileHeader)
If you can switch to function components and the useSelector/useDispatch hooks you should. This is the current recommended approach and it's easier to use.

TypeError: dispatch on action execution

In this my action the user's log out of my application is exported in react
export const logoutUser = () => {
return dispatch => {
dispatch(
{
type: LOGOUT_USER
}
)
.then(() => {
logoutUserSuccess(dispatch, )
})
.catch((err) => {
logoutUserError(err, dispatch)
})
}
}
const logoutUserSuccess = (dispatch) => {
dispatch(
{
type: LOGOUT_USER_SUCCESS
}
)
AsyncStorage.removeItem('#token_jwt')
console.log('saiu')
Actions.loginScreen()
}
const logoutUserError = (err, dispatch) => {
dispatch(
{
type: LOGOUT_USER_ERROR
}
)
Alert.alert('Erro ao sair da conta')
console.log(err)
}
is my Reducer
case LOGOUT_USER:
return {
...state
}
case LOGOUT_USER_SUCCESS:
return {
INITIAL_STATE
}
case LOGOUT_USER_ERROR:
return {
...state
}
is my screen to logout
onLogout() {
this.props.logoutUser()
}
const mapStateToProps = state => (
{
email: state.Authentication.email
}
)
export default connect(mapStateToProps, { logoutUser })(Home)
The return is the following error
I put the email on the mapStateToProps, because I don't know how to leave it blank, what matters to me is the logout
You can try creating a mapDispatchToProps function and dispatch the action logoutUser from inside the function and pass it as a second argument to connect.
In doing so, you can invoke the LogoutUser from mapDispatchToProps in your onLogout function.
import {logoutUser} from './youractions.js'
onLogout() {
this.props.LogoutUser();
}
const mapDispatchToProps = (dispatch) => ({
LogoutUser: () => dispatch(logoutUser()),
});
export default connect(null, mapDispatchToProps)(Home);

Redux doesn't fetch data from API request

I'm new to React/Redux. I'm making an app using an API but the code doesn't work. When I run the code it says "this.props.recipes.map is not a function" and doesn't render anything.
If I change payload to: "payload: response.data.recipes" then the error changes to "Given action "FETCH_RECIPE", reducer "recipes" returned undefined." but no errors on screen (only in console). I thought writing "(state = [], action)" would solve the problem but it seems not. What's the problem and how do I fix this error?
Action Creator
import recipe from '../apis/recipe';
export const fetchRecipe = () => async dispatch => {
const response = await recipe.get('');
dispatch({ type: 'FETCH_RECIPE', payload: response.data })
};
Reducer
import { combineReducers } from 'redux';
const recipeReducer = (state = [], action) => {
switch(action.type) {
case 'FETCH_RECIPE':
return action.payload;
default:
return state;
}
};
export default combineReducers({
recipes: recipeReducer
});
import React from 'react';
import { connect } from 'react-redux';
import { fetchRecipe } from '../actions';
class Recipe extends React.Component {
componentDidMount() {
this.props.fetchRecipe();
console.log("This doesn't work", this.props.recipes)
}
renderList() {
return this.props.recipes.map(recipe => {
return (
<div>
<p>{recipe.publisher}</p>
</div>
)
})
}
render() {
console.log("First loaded: empty, second time: data fetched", this.props.recipes)
return (
<div>
{this.renderList()}
</div>
);
}
}
const mapStateToProps = (state) => {
return { recipes: state.recipes }
};
export default connect(mapStateToProps,{
fetchRecipe
})(Recipe);
API Request
import axios from 'axios';
import { key } from './config';
export default axios.create({
baseURL: `https://cors-anywhere.herokuapp.com/https://www.food2fork.com/api/search?key=${key}&q=pizza`
});

mapDispatchToProps action is not a function

So I do this in container:
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators({fetchMarkers}, dispatch)
}
}
and when props is logged in browser I get:
actions: {
fetchMakers: function() ....
}
but when I call this.props.actions.fetchMarkers(params) I get the following error:
Cannot read property 'fetchMarkers' of undefined
This is driving me nuts, Please help!
Edit:
Action:
export const fetchMarkers = (payload) => {
return {
type: actionTypes.fetchMarkers,
payload
}
}
Try this case:
import { fetchMarkers } from 'path_to_makers_action';
....Code of react component....
export default connent(null, { fetchMarkers });
And in component you use: this.props.fetchMarkers()

Resources