I'm using redux with React to manage states but when I called two dispatch function from one action creator, it's return state from the first dispatch but unable to get updated state after another dispatch call.
I've tried to call dispatch from different reducers and tried to call after API call.
Here are my actions.
export const setLoader = (loader) => dispatch => {
dispatch({ type: SET_LOADER, payload: loader });
};
export const fetchCategory = (setLoader) => async dispatch => {
setLoader(true);
try {
const instance = axios.create();
instance.defaults.headers.common['Authorization'] = AUTHORIZATION_TOKEN;
const response = await instance.get(API_PATHS.SERVICE_CATEGORY_API);
dispatch({ type: FETCH_CATEGORY, payload: response.data });
} catch (e) {
setLoader(false);
}
};
Here i defined reducers:
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case FETCH_CATEGORY:
return { ...state, categoryList: action.payload };
case SET_LOADER:
return { ...state, isLoading: action.payload };
default:
return state;
}
};
Here my component connected with redux:
const mapStateToProps = state => {
return ({
categoryList: state.locator.categoryList
});
}
export default connect(
mapStateToProps,
{ fetchCategory, setLoader }
)(ServiceLocator);
I expect the output to return updated categoryList, but the actual it returns a blank array.
You are performing an asynchronous task in your action creator, which Redux can't handle without a middleware. I recommend using the middleware redux-thunk. This will allow you to perform asynchronous actions in your action creators and dispatch multiple times.
Hope this helps!
UPDATE:
If you have the redux-think middleware installed and added to Redux (per your comment), then next I would look at setLoader() - it looks like that function is curried and I don't think you want it to be. I would remove the setLoader() step and dispatch that action directly from fetchCategory():
export const fetchCategory = () => async dispatch => {
dispatch({ type: SET_LOADER, payload: true });
try {
const instance = axios.create();
instance.defaults.headers.common['Authorization'] = AUTHORIZATION_TOKEN;
const response = await instance.get(API_PATHS.SERVICE_CATEGORY_API);
dispatch({ type: FETCH_CATEGORY, payload: response.data });
} catch (e) {
dispatch({ type: SET_LOADER, payload: false });
}
};
Related
// action
export const getEvents = () => async (dispatch) => {
try {
dispatch({ type: GET_EVENTS_REQUEST })
const data = await axios.get('http://localhost:5000/api/schedule').then((response) => response.data)
dispatch({ type: GET_EVENTS_SUCCESS, payload: data })
} catch (error) {
dispatch({
type: GET_EVENTS_FAIL,
payload:
error.response && error.response.data.message
? error.response.data.message
: error.message,
})
}
}
// reducer
export const getEventsReducer = (state = { event: [] }, action) => {
switch (action.type) {
case GET_EVENTS_REQUEST:
return { loading: true }
case GET_EVENTS_SUCCESS:
return { loading: false, event: action.payload }
case GET_EVENTS_FAIL:
return { loading: false, error: action.payload }
default:
return state
}
}
// and this is how I'm trying to call my action:
import { getEvents } from '../../redux/actions/calendarActions'
class Calendar extends React.PureComponent {
componentDidMount() {
const { dispatch } = this.props
console.log(dispatch(getEvents()))
}
}
export default connect()(Calendar)
// component is much bigger, I only added relevant parts
Up until my reducer, if I console.log my data, it is correct, as well as in my redux dev tools tab: an array with a few entries. But when console.logging in my Calendar component, it returns a promise, with undefined result:
Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined
What am I doing wrong?
Normally you want to have access to either the dispatch or the store of Redux within a component. you already have the dispatch function within the component, but if you need access to Redux state inside it:
first you need to define such function, which makes the redux store available in the component.
const mapStateToProps = (state) => ({
state: state // a "state" prop is available in the component which points to redux state,
})
or you can customize it if you only need certain properties of Redux state:
const mapStateToProps = (state) => ({
state: state.event //
})
and change the connect function like this:
connect(mapStateToProps)(Calendar)
I made a todo list a while ago as a way to practice react and redux. Now I'm trying to rewrite it with redux toolkit and having some trouble with the action creators.
Here is the old actions creator:
export const changeDescription = (event) => ({
type: 'DESCRIPTION_CHANGED',
payload: event.target.value })
export const search = () => {
return (dispatch, getState) => {
const description = getState().todo.description
const search = description ? `&description__regex=/${description}/` : ''
axios.get(`${URL}?sort=-createdAt${search}`)
.then(resp => dispatch({ type: 'TODO_SEARCHED', payload: resp.data }))
} }
export const add = (description) => {
return dispatch => {
axios.post(URL, { description })
.then(() => dispatch(clear()))
.then(() => dispatch(search()))
} }
export const markAsDone = (todo) => {
return dispatch => {
axios.put(`${URL}/${todo._id}`, { ...todo, done: true })
.then(() => dispatch(search()))
} }
export const markAsPending = (todo) => {
return dispatch => {
axios.put(`${URL}/${todo._id}`, { ...todo, done: false })
.then(() => dispatch(search()))
} }
export const remove = (todo) => {
return dispatch => {
axios.delete(`${URL}/${todo._id}`)
.then(() => dispatch(search()))
} }
export const clear = () => {
return [{ type: 'TODO_CLEAR' }, search()] }
Now this is the one that I'm working on, I'm trying to replicate the actions of the old one but using redux toolkit:
export const fetchTodos = createAsyncThunk('fetchTodos', async (thunkAPI) => {
const description = thunkAPI.getState().todo.description
const search = description ? `&description__regex=/${description}/` : ''
const response = await axios.get(`${URL}?sort=-createdAt${search}`)
return response.data
})
export const addTodos = createAsyncThunk('fetchTodos', async (thunkAPI) => {
const description = thunkAPI.getState().todo.description
const response = await axios.post(URL, {description})
return response.data
})
export const todoReducer = createSlice({
name: 'counter',
initialState: {
description: '',
list: []
},
reducers: {
descriptionChanged(state, action) {
return {...state, dedescription: action.payload}
},
descriptionCleared(state, action) {
return {...state, dedescription: ''}
},
},
extraReducers: builder => {
builder
.addCase(fetchTodos.fulfilled, (state, action) => {
const todo = action.payload
return {...state, list: action.payload}
})
.addCase(addTodos.fulfilled, (state, action) => {
let newList = state.list
newList.push(action.payload)
return {...state, list: newList}
})
}
})
The thing is, I can't find anywhere how to export my extra reducers so I can use them. Haven't found anything in the docs. Can someone help?
extraReducers
Calling createSlice creates a slice object with properties reducers and actions based on your arguments. The difference between reducers and extraReducers is that only the reducers property generates matching action creators. But both will add the necessary functionality to the reducer.
You have correctly included your thunk reducers in the extraReducers property because you don't need to generate action creators for these, since you'll use your thunk action creator.
You can just export todoReducer.reducer (personaly I would call it todoSlice). The reducer function that is created includes both the reducers and the extra reducers.
Edit: Actions vs. Reducers
It seems that you are confused by some of the terminology here. The slice object created by createSlice (your todoReducer variable) is an object which contains both a reducer and actions.
The reducer is a single function which takes the previous state and an action and returns the next state. The only place in your app when you use the reducer is to create the store (by calling createStore or configureStore).
An action in redux are the things that you dispatch. You will use these in your components. In your code there are four action creator functions: two which you created with createAsyncThunk and two which were created by createSlice. Those two will be in the actions object todoReducer.actions.
Exporting Individually
You can export each of your action creators individually and import them like:
import {fetchTodos, descriptionChanged} from "./path/file";
Your fetchTodos and addTodos are already exported. The other two you can destructure and export like this:
export const {descriptionChanged, descriptionCleared} = todoReducer.actions;
You would call them in your components like:
dispatch(fetchTodos())
Exporting Together
You might instead choose to export a single object with all of your actions. In order to do that you would combine your thunks with the slice action creators.
export const todoActions = {
...todoReducer.actions,
fetchTodos,
addTodos
}
You would import like this:
import {todoActions} from "./path/file";
And call like this:
dispatch(todoActions.fetchTodos())
I'm trying to create a loading state for my Redux but it looks to "slow" to get updated.
First action fetchDB => setLoading: true => once over setLoading: false
Second action fetchCat => doesn't have the time to fire it that crashes
Really simple:
set loading action:
export const setLoading = () => {
return async (dispatch) => {
await dispatch({ type: SET_LOADING }); // no payload by default goes to true
};
};
set loading reducer:
import {
FETCH_DB,
SET_LOADING,
} from "../types"
const initalState = {
db: [],
loading: false,
}
export default (state = initalState, action) => {
switch (action.type) {
// this like the other cases sets loading to FALSE
case FETCH_DB:
return {
...state,
db: action.payload,
current: null,
loading: false,
}
case FETCH_CAT_FOOD:
return {
...state,
food: action.payload,
loading: false,
}
case FETCH_CAT_DESIGN:
return {
...state,
design: action.payload,
loading: false,
}
case SET_LOADING:
return {
...state,
loading: true,
}
default:
return state
}
}
then action I use that creates the problem:
export const fetchCat = kindof => {
return async dispatch => {
dispatch(setLoading()) // looks like that it doesn't get fired
const response = await axios
.get(`http://localhost:5000/api/categories/${kindof}`)
.then(results => results.data)
try {
await dispatch({ type: `FETCH_CAT_${kindof}`, payload: response })
} catch (error) {
console.log("await error", error)
}
}
}
and then the file (a custom component) that creates the problem.
It crashes cause categories.map is undefined.
It doesn't find loading: true so the loader doesn't stop.
import React, { useState, useEffect, Fragment } from "react"
import { Spinner } from "react-bootstrap"
import { connect, useDispatch, useSelector } from "react-redux"
import CatItem from "./CatItem" // custom component
import { fetchCat, setLoading } from "../../../store/actions/appActions"
const MapCat = ({ kindof, loading, categories }) => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(fetchCat(kindof)) // gives the category I want to fetch
// eslint-disable-next-line
}, [categories])
if (!loading) {
return (
<Spinner animation="border" role="status">
<span className="sr-only">Loading...</span>
</Spinner>
)
} else {
return (
<Fragment>
<div>
{categories.map(item => (
<CatItem item={item} />
))}
</div>
</Fragment>
)
}
}
const mapStateToProps = (state, kindof) =>
({
loading: state.appDb.loading,
categories: state.appDb[kindof],
})
export default connect(mapStateToProps, { fetchCat, setLoading })(MapCat)
I think that it is supposed to work like this:
loading: false (by default) => true => time to fetch => false
But doesn't look like working. Any idea?
Firstly setLoading needs to return a plain object with type and payload
export const setLoading = () => ({ type: SET_LOADING });
In fetchCat the then is not required. Also async await for dispatch is not required.
export const fetchCat = (kindof) => {
return (dispatch) => {
dispatch(setLoading()); //<---this should now be ok.
const response = await axios.get(`http://localhost:5000/api/categories/${kindof}`)
// .then((results) => results.data); //<----- not required as you are using await
try {
dispatch({ type: `FETCH_CAT_${kindof}`, payload: response.data }); //<--- use response.data ...also async/await for dispatch is not rquired.
} catch (error) {
console.log("await error", error);
}
};
};
The 2nd arg of mapStateToProps is ownProps which is an object
const mapStateToProps = (state, ownProps) =>
({
loading: state.appDb.loading,
categories: state.appDb[ownProps.kindof],
})
You have quite a bit different way of calling dispatch. Let me list them out
dispatch(fetchCat(kindof)) // gives the category I want to fetch
await dispatch({ type: `FETCH_CAT_${kindof}`, payload: response })
You can see, await or not basically is the way you use async operation. However dispatch takes type and payload to function, which means you have to make sure what you send to dispatch is with the right object. Of course Redux does accept custom format via plugins, so maybe if you throw it a async as input, the reducer might understand it as well?
Please double check each dispatch first, for example, write a function that only dispatch one type of action. Only after you make each call working, don't move to assemble them together into a bundled call.
I am trying to dispatch functions from reducer but it call only one function.
Reducer looks like this:
import types from "./types";
const initState = {
active: false,
myData: []
};
function toggleActive(state, action) {
return {
...state,
active: action.payload
};
}
function watchInfo(state, action) {
return {
...state,
myData: action.payload
};
}
const watchReducer = (state = initState, action) => {
switch (action.type) {
case types.TOGGLE_ACTIVE:
return toggleActive(state, action);
case types.WATCH_DATA:
return watchInfo(state, action);
default:
return state;
}
};
export default watchReducer;
and action creator is set like this:
import types from "./types";
function toggleActive(bool) {
return {
type: types.TOGGLE_ACTIVE,
payload: bool
};
}
function watchInfo(data) {
return dispatch => {
dispatch({
type: types.WATCH_DATA,
payload: data
});
};
}
export { toggleActive as default, watchInfo };
and in component in which I am importing connect and corresponding action creator, i am trying to use it like this:
const mapStateToProps = state => {
const mapDispatchToProps = dispatch => ({
watchInfo: () => dispatch(watchInfo())
});
export default connect
mapDispatchToProps
)(MyComponent);
So when I inspect in redux console it only calls toggleActive, never calls watch info.
I am not sure what I am doing wrong.
change this action creator
function watchInfo(data) {
return dispatch => {
dispatch({
type: types.WATCH_DATA,
payload: data
});
};
}
to:
function watchInfo(data) {
return {
type: types.WATCH_DATA,
payload: data
}
}
action creator is a function that return an object that representing an action. we use action creators for better code maintenance and prevent some Spelling error but this code:
dispatch(watchInfo(someData))
is equivalent to this:
dispatch({
type: types.WATCH_DATA,
payload: someData
})
I'm getting an object from an action (using axios) and using a map function to iterate it.
I also need to get another action but inside the parent object mapped.
I see that the request/response are ok (with returned data), but the reducer variable still gets empty.
1: component gets data
componentDidMount() {
const { match: { params } } = this.props;
this.props.getSaleDetails(params.order_id);
}
2: defining mapStateToProps and mapDispatchToProps
const mapStateToPropos = state => ({
saleDetails: state.salesOrders.saleDetails,
saleDetailFurthers: state.salesOrders.saleDetailFurthers
});
const mapDispatchToProps = dispatch =>
bindActionCreators({ getSaleDetails, getDetailFurthers }, dispatch);
3: creating a const from the redux props
const detailsArray = saleDetails.data;
4: iterate array with map function
// getDetailFurthers is another action, getting data by passing "detail_id" and updating "saleDetailFurthers" props
{detailsArray && detailsArray.map((item) => {
const {getDetailFurthers, saleDetailFurthers} = this.props;
getDetailFurthers(item.detail_id)
console.log(saleDetailFurthers)
// empty array????
count++;
return (
<Paper className={classes.paper} key={item.detail_id}>
// ... next code lines
5: Actions
export function getDetailFurthers(detail_id){
return async dispatch => {
const request = await axios.get(`${BASE_URL}/salesorders/detail/furthers/${detail_id}`)
return {
type: "SALE_DETAIL_FURTHERS_FETCHED",
payload: request
}
}
}
6: Reducers
const INITIAL_STATE = {
//... others
saleDetailFurthers: []
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
///... other cases
case "SALE_DETAIL_FURTHERS_FETCHED":
return { ...state, saleDetailFurthers: action.payload }
default:
return state
}
};
I expect the "saleDetailFurthers" const be loaded with data from redux action.
You need to use dispatch instead of returning, like so:
dispatch({
type: "SALE_DETAIL_FURTHERS_FETCHED",
payload: request
});
export function getDetailFurthers(detail_id) => dispatch =>{
const request = await axios.get(`${BASE_URL}/salesorders/detail/furthers/${detail_id}`)
dispatch ({
type: "SALE_DETAIL_FURTHERS_FETCHED",
payload: request
})
}