Redux - thunkMiddleware - dispatch as an extra argument doesn't work - javascript

Why isn't dispatch read in fetchit()?
thunkMiddleware is added to applyMiddleware
introduce dispatch to fetchit in mapDispatchToProps
dispatch is added as an extra argument in fetchit()
I can go around this and make it work in other ways like for example, initializing a global variable "dispatch" and in the component -> dispatch = useDispatch() ... and multiple other ways ...
But I found online that doing it in this particular way should work, so I was wondering what is missing here...
import React from 'react';
import { createStore, applyMiddleware} from "redux";
import loggerMiddleware from "redux-logger";
import { connect } from 'react-redux'
import { useRef } from 'react';
import thunkMiddleware from "redux-thunk";
const ADD_TASK = "addTask";
const addTask = (task) => {return ({
type: ADD_TASK,
payload: task
})}
const reducer = (state=[], action) => {
switch (action.type){
case ADD_TASK:
return [...state, ...action.payload];
default:
return state;
}
}
export const store = createStore(reducer, applyMiddleware(thunkMiddleware,loggerMiddleware));
const fetchit = (newTask="") =>(dispatch)=>{
console.log(">>>>>>>>>>>>>>>",dispatch); // <<<<<<<<<<<< dispatch is not read
if (!newTask){
fetch("/get")
.then(response => response.json())
.then(result => {
dispatch(addTask(result.tasks));
})
.then(()=>{
document.documentElement.scrollIntoView(false);
})
}
else {
fetch("/add", {
credentials: "include",
method: "POST",
mode: "same-origin",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
//"X-CSRFToken": csrf
},
body: JSON.stringify(newTask),
})
.then(response => response.json())
.then(result => {
if (result.task)
dispatch(addTask([result.task]));
})
.then(()=>{
document.documentElement.scrollIntoView(false);
})
}
}
const Tasks = (props) => {
const {state} = props;
return [state.map(task => (
<li key={task.id} style={{color:task.done?"blue":"red"}}>
{task.task} <section style={{color:"black"}}>{task.description}</section>
<section style={{color:"lightgray"}}>{task.dateTime}</section>
</li>
))]
}
var firstFetch = true;
const App = (props) => {
if (firstFetch){
firstFetch = false;
fetchit();
}
const inputTask = useRef(null);
const inputDescription = useRef(null);
const fetchNewInput = () => {
let bodydict = {"task": inputTask.current.value, "description": inputDescription.current.value};
fetchit(bodydict);
inputTask.current.value = "";
inputDescription.current.value = "";
}
return <>
<h1>Tasks</h1>
<ol>
<Tasks state={props.state || []}/>
</ol>
<div>
<input ref={inputTask}/>
<textarea ref={inputDescription}></textarea>
<button onClick={fetchNewInput}>ADD</button>
</div>
</>
}
const mapStateToProps = (state) => {
return {state: state};
}
const mapDispatchToProps = (dispatch) => {return {
fetchit:(something)=> dispatch(fetchit(something)),
addTask: (something) => dispatch(addTask(something)),
}}
export default connect(mapStateToProps, mapDispatchToProps)(App);
The missed step --> extracting functions from props
const App = ({fetchit}) => {}

In this section:
const fetchNewInput = () => {
let bodydict = {"task": inputTask.current.value, "description": inputDescription.current.value};
fetchit(bodydict);
inputTask.current.value = "";
inputDescription.current.value = "";
}
you are calling the thunk itself, while you should dispatch fetchit. you have access to dispatching fetchit via props.fetchit, as you defined in mapDispatchToProps
props.fetchit(bodydict);
I guess the same naming got you confused.
also, you can dispatch addTask like this:
props.addTask(task);

Related

react/redux fetching data from redux slice issue

I am creating a react/ redux app using json fake api server redux toolkit.
I am adding a some datas from and api to redux slice and trying to retrieve to my component. data seems empty and no error showing could anyone able to help me in this if possible.
my redux slice
import {
createAsyncThunk,
createSlice,
createSelector,
} from "#reduxjs/toolkit";
import axios from "axios";
import { base_emp } from "./api";
const initialState = {
emplist: [],
loading: "loading",
};
export const fetchEmployees = createAsyncThunk(
"employee/emplist",
async (_, thunkAPI) => {
try {
const response = await axios.get(base_emp);
return await response.json();
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message });
}
}
);
export const userSlice = createSlice({
name: "user",
initialState,
// The `reducers` field lets us define reducers and generate associated actions
reducers: {
decrement: (state) => {
state.value -= 1;
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
extraReducers: (builder) => {
builder.addCase(fetchEmployees.pending, (state) => {
state.emplist = [];
state.loading = "loading";
});
builder.addCase(fetchEmployees.fulfilled, (state, { payload }) => {
state.emplist = payload;
state.loading = "loaded";
});
builder.addCase(fetchEmployees.rejected, (state, action) => {
state.loading = "error";
state.error = action.error.message;
});
},
});
export const { increment, decrement, incrementByAmount } = userSlice.actions;
export const selectCount = (state) => state.counter.value;
export const selectEmployees = createSelector(
(state) => ({
products: state.emplist,
loading: state.loading,
}),
(state) => state
);
export default userSlice.reducer;
my component goes here
import React, { useState, useEffect } from "react";
import EmployeeDetails from "./EmployeeDetails";
import { useSelector, useDispatch } from "react-redux";
import { fetchEmployees, selectEmployees } from "./features/auth/userSlice";
const Employelist = () => {
const [employe, setEmployee] = useState([]);
const dispatch = useDispatch();
const { emplist } = useSelector(selectEmployees);
React.useEffect(() => {
dispatch(fetchEmployees());
}, [dispatch]);
useEffect(() => {
emplist &&
emplist.then((res) => res.json()).then((data) => setEmployee(data));
}, []);
const handleclick = (id) => {
const emp = employe.filter((emp) => emp.employeeid !== id);
setEmployee(emp);
};
// console.log(currentUsers);
return (
<div>
<EmployeeDetails handleclick={handleclick} employe={employe} />
</div>
);
};
export default Employelist;
api.js
import axios from "axios";
export const base_emp = axios.get("http://localhost:5000/emp");
error message in console

React-Redux: Action is Dispatched but Reducer is not updating the state

I'm trying to check if my store is onboarded or not. for that, I'm making an API call through the redux to check it in the BE and if it's true I'll redirect it to the dashboard. I'm able to get the data successfully from BE, and on success checkIsStoreOnboardedSuccess() is called but in the reducer, the state is not updated with the CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_SUCCESS state in the reducer.
action.js
import * as actionTypes from './index';
import API from '../../api';
export const clearCheckIsStoreOnboarded = () => {
return {
type: actionTypes.CLEAR_CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING,
};
};
export const checkIsStoreOnboarded = (payload) => {
return (dispatch) => {
dispatch(checkIsStoreOnboardedInitiate());
API.getAccountSettings(payload)
.then((response) => {
checkIsStoreOnboardedSuccess(response.data);
})
.catch((err) => {
checkIsStoreOnboardedFailure(err);
});
};
};
const checkIsStoreOnboardedInitiate = () => {
return {
type: actionTypes.CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_START,
};
};
const checkIsStoreOnboardedSuccess = (data) => {
return {
type: actionTypes.CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_SUCCESS,
data: data,
};
};
const checkIsStoreOnboardedFailure = (err) => {
return {
type: actionTypes.CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_FAIL,
data: err,
};
};
reducer.js
import * as actionTypes from '../actions';
const initialState = {
isLoading: true,
isError: false,
isDone: false,
data: [],
error: null,
};
const clearCheckIsStoreOnboarded = () => {
return initialState;
};
const checkIsStoreOnboardedStart = (state) => {
return { ...state, isLoading: true, error: null, isError: false };
};
const checkIsStoreOnboardedSuccess = (state, action) => {
return { ...state, data: action.data, isDone: true, isLoading: false };
};
const checkIsStoreOnboardedFailure = (state, action) => {
return { ...state, error: action.data, isLoading: false, isError: true };
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.CLEAR_CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING:
return clearCheckIsStoreOnboarded();
case actionTypes.CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_START:
return checkIsStoreOnboardedStart(state);
case actionTypes.CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_SUCCESS:
return checkIsStoreOnboardedSuccess(state, action);
case actionTypes.CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_FAIL:
return checkIsStoreOnboardedFailure(state, action);
default:
return state;
}
};
export default reducer;
actionTypes.js
export const CLEAR_CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING = 'CLEAR_CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING';
export const CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_START = 'CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_START';
export const CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_SUCCESS = 'CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_SUCCESS';
export const CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_FAIL = 'CHECK_IS_STORE_ONBOARDED_FOR_ONBOARDING_FAIL';
onboard.js
import React, { useState, useEffect } from 'react';
import { withCookies } from 'react-cookie';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import Crew from './Crew';
import Service from './Services';
import Address from './Address';
import { useStyles } from './css/index.css';
import Header from './header';
import Stepper from './stepper';
import { getStoreID } from '../../../utils';
import {
clearCheckIsStoreOnboarded,
checkIsStoreOnboarded,
} from '../../../store/actions/check-is-store-onboarded-for-onboarding'
import Loader from '../../../components/CircularProgressLoader';
const OnboardScreen = ({
cookies,
clearCheckIsStoreOnboarded,
checkIsStoreOnboarded,
checkIsStoreOnboardedData,
}) => {
const [step, setStep] = useState(0);
// eslint-disable-next-line no-unused-vars
const [width, isDesktop] = useWindowWitdh();
const classes = useStyles(isDesktop);
const store_id = getStoreID(cookies);
useEffect(() => {
checkIsStoreOnboarded({
store_id,
});
}, []);
useEffect(() => () => clearCheckIsStoreOnboarded(), []);
if(checkIsStoreOnboarded.isDone){
<Redirect to='/dashboard'>
}
const updateStep = () => {
const updatedStep = step + 1;
setStep(updatedStep);
};
const onboardingScreenToRender = () => {
switch (step) {
case 0:
return (
<Crew />
);
case 1:
return (
<Service />
);
case 2:
return <Address />;
}
};
return (
<div className={classes.container}>
<Header isDesktop={isDesktop} />
<div className={classes.contentOfContainer}>
<div className={classes.titleHeader}>
Onboarding
</div>
<Stepper stepNumber={step} setStepNumber={setStep} />
{checkIsStoreOnboardedData.isLoading && <Loader />}
</div>
</div>
// <OnboardLoader />
);
};
const mapStateToProps = (state, ownProps) => {
return {
...ownProps,
checkIsStoreOnboardedData: state.checkIsStoreOnboardedForOnboardingReducer
};
};
const mapDispatchToProps = (dispatch) => {
return {
checkIsStoreOnboarded: (payload) => dispatch(checkIsStoreOnboarded(payload)),
clearCheckIsStoreOnboarded: () => dispatch(clearCheckIsStoreOnboarded()),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(withCookies(OnboardScreen));
You need to dispatch your actions:
export const checkIsStoreOnboarded = (payload) => {
return (dispatch) => {
dispatch(checkIsStoreOnboardedInitiate());
API.getAccountSettings(payload)
.then((response) => {
// here
dispatch(checkIsStoreOnboardedSuccess(response.data));
})
.catch((err) => {
// and here
dispatch(checkIsStoreOnboardedFailure(err)(;
});
};
};
That said: you are writing a very outdated style of Redux here - in modern Redux, all of that would probably be possible with 1/4 of the code. If you are just learning Redux, you are probably following a very outdated tutorial. Modern Redux does not require you to write action type strings or action creators and your reducers can contain mutable logic. Also, it does not use connect unless you are working with legacy class components (which you don't seem to be doing).
I really recommend you to read the official Redux tutorial at https://redux.js.org/tutorials/essentials/part-1-overview-concepts

React renders my Component before it actually has Data

So I'm hard stuck on this Problem... normally I would just do a "ComponentDidMount" but since I'm trying to avoid using classes and only use react hooks I got stuck with the Problem.
My Component renders before it gets any Data from the API, so my .map function won't work as it has not recieve any data.
Shop.js
import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { listShops } from "../../Redux/actions/shopActions";
const Shop = () => {
const userShop = useSelector(state => state.shop);
const auth = useSelector(state => state.auth);
const dispatch = useDispatch();
useEffect(() => {
dispatch(listShops(auth));
}, []);
console.log("Look at my userShop",userShop.shop)
return (
<div>
{userShop.map(shop=>(<div>{shop}</div>))}
{console.log("How often do I Render?")}
</div>
);
};
export default Shop;
ShopAction.js
import {GET_SHOPS} from "./types";
export const listShops = userData => async dispatch =>{
const userId = userData.user.id;
await axios.get(`/api/shops/shops/user/${userId}`)
.then(
res => {
const user = res.data;
dispatch({
type: GET_SHOPS,
payload: user.shops
})})
}
shopReducer.js
const initialState = {}
export default function(state = initialState, action) {
switch (action.type) {
case GET_SHOPS:
return {
...state,
shop:action.payload
}
default:
return state;
}
}
if(!userShop){
return <h1>loading<h1>;
}
return (
<div>
{userShop.map(shop=>(<div>{shop}</div>))}
</div>
);
Return an empty array if state.shop is undefined using short-circuit evaluation:
const userShop = useSelector(state => state.shop || []);
return (
<div>
{userShop && userShop.map(shop=>(<div>{shop}</div>))}
</div>
);

Calling a function inside another function after receiving the data in react redux

How to call the getTodo function inside thegetTodos function if I receive data. if (data) {getTodo ()}? Expected effect of click button -> call functiongetTodos -> if (data) {getTodo ()}.
I'm trying to call getTodo () like this in actions:
.then (({data}) => {
dispatch ({type: GET_TODOS, payload:
date
});
}, () => getTodo ())
Demo here: https://stackblitz.com/edit/react-iuvdna?file=actions%2Findex.js
actions
import axios from 'axios';
export const GET_TODOS = 'GET_TODOS';
export const GET_TODO = 'GET_TODO';
export const FETCH_FAILURE = 'FETCH_FAILURE';
export const getTodos = () =>
dispatch => {
return axios({
url: 'https://jsonplaceholder.typicode.com/todos',
method: 'GET',
})
.then(({data})=> {
dispatch({type: GET_TODOS, payload:
data
});
},() => getTodo())
.catch(error => {
console.log(error);
dispatch({type: FETCH_FAILURE})
});
};
export const getTodo = () =>
dispatch => {
return axios({
url: 'https://jsonplaceholder.typicode.com/todos/1',
method: 'GET',
})
.then(({data})=> {
dispatch({type: GET_TODO, payload:
data
});
})
.catch(error => {
console.log(error);
dispatch({type: FETCH_FAILURE})
});
};
reducers
import {GET_TODOS, GET_TODO} from '../../actions';
import { combineReducers } from 'redux';
const todos = (state = [], action) => {
const { type, payload } = action;
switch (action.type) {
case 'GET_TODOS':
return payload;
default:
return state;
}
};
const todo = (state = {}, action) => {
const { type, payload } = action;
switch (action.type) {
case 'GET_TODO':
return payload;
default:
return state;
}
};
const rootReducer = combineReducers({
todos,
todo
});
export default rootReducer;
Todos
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {getTodos, clearTodos, getTodo} from '../.././actions';
class Todos extends Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<button onClick={this.props.getTodos}>Get Todos</button>
<ul>
{this.props.todos.map(todo => {
return <li key={todo.id}>
{todo.title}
</li>
})}
</ul>
{this.props.todo.id}
</div>
);
}
}
const mapStateToProps = state => {
const { todos, todo } = state;
return {
todos,
todo
};
};
const mapDispatchToProps = dispatch => ({
getTodos: () => dispatch(getTodos()),
getTodo: () => dispatch(getTodo())
});
export default connect(mapStateToProps, mapDispatchToProps)(Todos);

Updating redux state onClick

I have a component that displays data from the state. I'm using redux for state. I want to be able to click a button and filter the state. But I'm stuck on dispatching the action from the button.
Right now I have a button that is supposed to dispatch the action but it's not being called. I'm not sure if the mapsToDispatchProps is wrong or it's something else.
Here is the actions
import { GET_POLLS, SHOW_APPROVAL } from './types';
const URL = 'https://projects.fivethirtyeight.com/polls/polls.json';
export const getPolls = () => dispatch => {
return fetch(URL)
.then(res => res.json())
.then(polls => {
dispatch({ type: GET_POLLS, payload: polls })
})
}
export const getApproval = () => ({ type: SHOW_APPROVAL })
reducer
import {
GET_POLLS,
SHOW_APPROVAL
} from '../actions/types';
const pollReducer = (state = [], { type, payload }) => {
switch (type) {
case GET_POLLS:
return payload
case SHOW_APPROVAL:
return (payload.type === "trump-approval")
default:
return state
}
}
export default pollReducer;
types
export const GET_POLLS = 'GET_POLLS';
export const POLLS_LOADING = 'POLLS_LOADING';
export const SHOW_ALL = 'SHOW_ALL';
export const SHOW_APPROVAL = 'SHOW_APPROVAL';
list that displays data
import React, { Component } from 'react'
import { PollCard } from '../Components/PollCard'
// import FilterLink from './FilterLink'
import * as moment from 'moment';
import { connect } from 'react-redux'
import { getPolls, getApproval } from '../actions/index';
class PollList extends Component {
componentDidMount() {
this.props.getPolls();
}
render() {
console.log("rendering list")
const { polls } = this.props
const range = 30
var dateRange = moment().subtract(range, 'days').calendar();
var filteredPolls = polls.filter(e => Date.parse(e.endDate) >= Date.parse(dateRange)).reverse()
return (
<React.Fragment>
<button onClick={getApproval}>
Get Approval
</button>
{console.log("get approval", getApproval)}
{
filteredPolls && filteredPolls.map((poll) => (
<div key={poll.id}>
<PollCard poll={poll} />
{/* {(poll.type)} */}
</div>
))
}
</React.Fragment>
)
}
}
const mapStateToProps = state => ({
polls: state.polls
});
const mapDispatchToProps = {
getApproval
};
export default connect(
mapStateToProps,
mapDispatchToProps,
{ getPolls, getApproval }
)(PollList);
// export default PollList;
Your mapDispatchToProps() appears to be configured incorrectly. You need to define a function that returns an object, defining a key-value pair for each action you want to make available as a prop in your component.
const mapDispatchToProps = (dispatch) => {
return {
getApproval: () => {
dispatch(getApproval())
},
getPolls: () => {
dispatch(getPolls())
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProp)(PollList);
Now getPolls is available as prop and you can use it in componentDidMount()
componentDidMount() {
this.props.getPolls();
}
You should also create an onClick handler for your getApproval action
handleClick = () => {
this.props.getApproval()
}
And then connect it to your onClick event-listener
<React.Fragment>
<button onClick={this.handleClick}>
Get Approval
</button>
console.log("get approval", getApproval)}
{
filteredPolls && filteredPolls.map((poll) => (
<div key={poll.id}>
<PollCard poll={poll} />
{/* {(poll.type)} */}
</div>
))
}
</React.Fragment>
Action File
export const getPolls = () => dispatch => {
fetch(URL)
.then(res => res.json())
.then(polls => {
dispatch({ type: GET_POLLS, payload: polls })
})
.catch(errors => {
dispatch({ type: "GET_ERRORS", payload: errors.response.data })
})
}
Reducer
import {
GET_POLLS,
SHOW_APPROVAL
} from '../actions/types';
const pollReducer = (state = [], { type, payload }) => {
switch (type) {
case GET_POLLS:
return payload
case SHOW_APPROVAL:
return state.filter((poll) => {
return poll.type === "trump-approval"
})
case "GET_ERRORS":
return payload
default:
return state
}
}
export default pollReducer;
You are not calling the action function.
// Either destructure it
const { polls, getApproval } = this.props;
<button onClick={getApproval}>
Get Approval
</button>
// Or use this.props.function
<button onClick={this.props.getApproval}>
Get Approval
</button>
// You don't need this
const mapDispatchToProps = {
getApproval
};
// You don't need this
const mapStateToProps = state => {
return {polls: state.polls};
};
export default connect(
mapStateToProps,
// Doing this is easier, cleaner & faster
{ getPolls, getApproval }
)(PollList);
Here you are doing it correctly;
componentDidMount() {
this.props.getPolls();
}

Categories

Resources