score:1
so this needs a very basic introduction to the flow of redux with 'side effects'.
the redux flow
- [view]your view reacts in various ways.
- [actions]we create an abstraction over these reactions called 'actions'.
- [dispatcher] this actions are dispatched to the store.
- [reducer] in the store we have logic written in 'reducers' that look at the actions and do manipulations to the store to update the store state.
- [state]this state is loaded on the react state tree.
definition alert! in redux stuff like calls to apis are called side effects. this is because you are doing something outside the typical unidirectional data flow.
hope you have understood this flow. i'm specifically concerned about a specific part that you seem to be confused about. so in your code you have tried to do this.
then(response => {
return dispatch(getaddress());
})
what your code is trying to do here is that, it's trying to 'dispatch' a side effect. this is wrong!
dispatch is almost always a plain old js object which is serializable. typically you will have stereotypical structure like this. which you seem to have in your other get address call.
{
type: 'get_address_request_success',
payload: {}
}
so the proper way to approach your task is like this. think of dispatching actions like emitting signals when various things happen.
export const login = (value, history) => dispatch => {
axios.post('/api/users/login', value)
.then(response => {
//send out a success signal
dispatch({
type: 'loginsuccess',
payload: response.data
});
//now that i have logged in successfully i can call for my address
//this is simply how you call an action within an action!
getaddress();
}).catch(error => {
//login failed signal
dispatch({
type: 'loginfailed',
payload: response
}); // i am calling like this
});
}
export const getaddress = () => dispatch => {
axios.get('/api/address')
.then(response => {
//get address success signal
dispatch({
type: 'getaddresssuccess',
payload: response.data
});
}).catch(function (error) {
//get addresses failed signal
dispatch({
type: 'getaddressfailed',
payload: error
});
});
}
the next important part is the reducer, which you have not included here! if actions emits signals think of the reducers as a receiver which receives and processes this signal. a reducer will update the existing state based on the action deployed.
export default function appreducer(state, action) {
switch (action.type) {
case 'getaddresssuccess': //waiting on the signal!
return object.assign({},state,{address : action.payload}
//set the proper address based on your payload from the api call
default:
return state
}
}
you also should have setup your redux thunk configuration properly for this to fully work. cheers!
============edit=============
so upon checking the codebase, you have used the combine reducer to meld multiple reducers together.
import { combinereducers } from 'redux';
import authreducer from './authreducer';
import addressreducer from './addressreducer';
const rootreducer = combinereducers({
authreducer,
addressreducer
});
export default rootreducer;
so in mapsstatetoprops your store state will look like this
{
authreducer: {
// state managed by the authreducer
},
addressreducer: {
address: 'test streat, london'
}
}
so change your mapstatetoprops to look like this
const mapstatetoprops = state => ({
addresses: state.addressreducer.address
});
export default connect(mapstatetoprops)(dashboard);
score:3
redux thunk middleware allows to chain via dispatch
, dispatch(...)
returns dispatched action, i.e. a promise if promise chains weren't broken:
export const login = (value, history) => dispatch => {
return axios.post('/api/users/login', value) // return!
.then(response => {
return dispatch(getaddress()); // return!
})
.catch(error => {});
}
export const getaddress = () => dispatch => {
return axios.get('/api/address') // return!
.then(response => {
return dispatch({ // return!
type: 'getaddresses',
payload: response.data
});
})
.catch(function (error) {});
}
initial action should be dispatched somewhere. in vanilla redux setup, it could be dispatched after store definition:
store.dispatch(login());
in react redux setup, components are integral parts of redux data flow. asynchronous thunk is a side effect and it should be dispatched once in componentdidmount
. in case of initial action, it should be dispatched in parent component:
@connect()
class app extends component {
componentdidmount() {
return this.props.dispatch(login());
}
render() {
return !this.props.addresses ? 'loading' : <dashboard />
}
}
here is a demo.
Source: stackoverflow.com
Related Query
- Calling an action in another action in Redux React
- React Redux dispatch action after another action
- Calling an action from a different reducer with React and redux
- React Redux : Action creator not calling reducer
- React + Redux App: Calling API through a Redux action Vs Calling an API directly
- React + Flux: best practice for calling an action after another action?
- React Redux - how to trigger action after another action without Component
- Calling one redux action from one store slice in another store slice
- React Router Link onClick redux action call not calling reducer
- Calling an action within another one in Redux using TypeScript
- React Redux, my component is not connected to Redux Store. I tested the action and reducer in another component, it does work for other components?
- How to call action in button click of component, Even though i'm using connect function which is not calling in React Redux
- react redux action not calling reducer
- Calling one function in another and passing it id, react + redux
- dispatch action and redirect by calling function without page reload in react redux ( Page Reload Problem )
- Wait for action creator to finish before calling another action creator - Redux thunk
- React Redux - Calling a function from within a simple action cause "not a function" error
- Calling another action after one is completed in React
- is there a way to call another action from one action in react redux
- React router redirect after action redux
- Transition to another route on successful async redux action
- Cannot read property '.then' of undefined when testing async action creators with redux and react
- Calling one action from another action creator
- Can I send an AJAX call in React and Redux without action creators and reducers?
- Redux - how to call an action creator from inside another action creator?
- how should I build onClick action in my react component + Redux
- redirect from redux action in react router v4
- Action does not trigger a reducer in React + Redux
- React Router + Redux - Dispatch an async action on route change?
- React Redux - How to dispatch an action on componentDidMount when using mapDispatchToProps in a connected component
More Query from same tag
- Dragging not working for react-use-gesture
- fetch multiple url in a object react
- Unable to batch.delete documents of a subcollection
- How to chain two filters in react.js
- How to render new React Component into rendered DOM?
- Router with render not passing props in another component
- (Using React) Why is the submit button when onClick is performed using onChange events and resulting in empty string? (useState question)
- How to embed a webpack bundled react app to another site
- Add/delete old rows dynamically using hooks reactjs
- How does the Client in a docker image know the ip address of a server which is in another docker image?
- How to display some content for dates in react-calendar when you hover a mouse on dates
- Formik. Dirty check
- How to resolve when create-react-app not responding in terminal
- When to use plain state over constructor(props)?
- React render multiple button with props
- React - (nested) prop type is invalid; it must be a function
- react js i am trying to make a pagination
- React router v6 nested routes not displaying child element
- How to prepend a list Item in react correctly
- Two setState second rely on first
- ESLint configuration in .eslintrc is invalid: - Unexpected top-level property "import/no-extraneous-dependencies"
- autoHideDuration not work with change on state
- How do I trigger a real error in Socket.io?
- Why doesn't my function action get called?
- React Firebase Integration - TypeError: firebase_app__WEBPACK_IMPORTED_MODULE_0__.default is undefined
- useEffect not producing data in console.log in sequence
- Stale items displayed in component
- How to hard code simple authentication (no backend) and redirect to home page - React
- How to use a variable in which data is fetched from mongoDB , in another file where we can use the data stored in that variable
- Get id from same element in ReactJS