I am quite new to JavaScript and react-native and I have existing project that I need to add functionality to. It is using redux and redux-thunk with redux-saga to send API requests. Currently it supports only 1 dispatch function per component and I need to dispatch several types of requests to the saga. I am trying to bindActionCreators to add the dispatch to the stores but to no avail.. I am totally lost on the mapDispatchToProps part and how do I "fire the action" afterwards..
in single dispatch to props, I did this:
let sdtp = (arg) => {
return (dispatch) => {
dispatch({
type: 'GET_TEST_HASHMAP_SAGA',
hashmap: arg
})
}
}
export default MainPage = connect(
mapStateToProps,
{ sdtp }
)(MainPage);
and I can "access the function" (is this the right term? at least my saga gets called) inside the MainPage.render() component :
`this.props.sdtp({'hello':'world'});`
but when I change to use bindActionCreators, I cannot access it in the props anymore (I have tried so many different experiments I almost give up)
Here is how I construct my multiple dispatches:
let action1 = (args) => {
return (dispatch) => {
dispatch({
type: 'GET_TEST_HASHMAP_SAGA',
hashmap: arg
});
}
}
let action2 = (args) => {
return (dispatch) => {
dispatch({
type: 'GET_TEST_HASHMAP_SAGA2',
params: arg
});
}
}
let action3 = (args) => {
return (dispatch) => {
dispatch({
type: 'GET_TEST_HASHMAP_SAGA3',
args: arg
});
}
}
let mdtp = (dispatch) => {
return {
actions: bindActionCreators(action1, action2, action3, dispatch)
}
}
export default MainPage = connect(
mapStateToProps,
{ mdtp }
)(MainPage);
I am trying to access the actions like this:
this.props.mdtp.action1({arg: 'hello'});
Thanks in advance!
connect takes four arguments...most people usually only need the first two.
mapStateToProps you have, and I'm assuming it's a function.
mapDispatchToProps is the second...the issue is there.
bindActionCreators is nothing but a for loop...leave it out and you will better understand what is happening.
Try this:
function mapDispatchToProps(dispatch) {
return {
action1: (args) => dispatch(action1(args)),
action2: (args) => dispatch(action2(args)),
}
}
export default MainPageContainer = connect(
mapStateToProps,
mapDispatchToProps
)(MainPage)
And call them as
this.props.action1(args) and this.props.action2(args)
If you insist on using the overrated bindActionCreators the syntax would be:
function mapDispatchToProps(dispatch){
return {
actions: bindActionCreators({
action1,
action2,
}, dispatch)
}
}
Also, use const instead of let since you are not redefining the value. It is also best to export the connected component under a different name than the class name of the component.
In your mpdt function, you need to return result of bindActionCreators call, not object with action key.
So, it should be
const mdtp = (dispatch) => {
return bindActionCreators({
action1, action2, action3
}, dispatch);
};
and you can call them as this.props.action1(...)
From your code it also seems, that you have confused two ways of passing action creators to the component. One way is described above. And another way, you can pass your action creators directly to connect() using object notations, like so
export default MainPage = connect(
mapStateToProps,
{ action1, action2, action3 }
)(MainPage);
which will have same result. And your first approach, with sdtp action creator uses this approach.
Alternatively, you can also skip mapDispatchToProps entirely..
Within your render() function, you can just call dispatch directly like this:
this.props.dispatch({type: 'GET_TEST_HASHMAP_SAGA2', params: {"hello": "world"}});
Then in your connect function, you can skip the mapDispatchToProps param entirely.
export default MainPage = connect(
mapStateToProps
)(MainPage);
I know this isn't the answer, but this is just an alternative that works as well
Related
I've a button that sends two actions. First one adds the user infos in an array if certain condition is met and 2nd one sends the data to the server.
Since both actions are in onPress function, the 2nd action doesn't wait till it adds up the infos in an array. Henceforth, it always sends empty array.
How can I make this two actions work simultaneously.
<TouchableOpacity
onPress={() => {
if (true) {
this.props.AuthUserInfoGet(SignUpName, SignUpDesignation, SignUpEmail, SignUpMobileNo); //calculates & return SignUpUsers
}
this.props.SignUpCheck(SignUpUsers); //upload SignUpUsers but SignUpCheck is always empty here
}}
>
<Text>Upload</Text>
</TouchableOpacity>
const mapStateToProps = (state) => {
const {SignUpUsers} = state.Auth;
//it gives an empty array first and then expected value
console.log('SignUpUsersz', SignUpUsers);
return {SignUpUsers};
};
Action:
export const AuthUserInfoGet = (SignUpName, SignUpDesignation, SignUpEmail, SignUpMobileNo) => {
return ({
type: SIGN_UP_USER_INFO_GET,
payloadName: SignUpName,
payloadDesignation: SignUpDesignation,
payloadEmail: SignUpEmail,
payloadMobile: SignUpMobileNo,
});
}
export const SignUpCheck = (userInfo) => {
console.log('userInfo', userInfo); // userInfo is always empty
}
Reducer:
const INITIAL_STATE = { SignUpUsers: [] }
case SIGN_UP_USER_INFO_GET:
return { ...state, SignUpUsers: [...state.SignUpUsers, {member_name: actions.payloadName, designation: actions.payloadDesignation,
email: actions.payloadEmail, mobile_number: actions.payloadMobile}] };
Given your current Redux-structure, I think what makes the most sense to use the componentDidUpdate life-cycle method.
The main reason is because your component ultimately needs to get updated data from Redux via props and needs to re-render. When you execute the first action, that user-data coming from the API is not immediately available in the current call-stack, so you'll always be passing an empty array (given your initial value of SignUpUsers: [])
Note that most React-Redux flows follow this path:
User-Event -> Action-Creator -> API (Data) -> Redux -> Component
Your click-event is at step 1 and triggers this action: this.props.AuthUserInfoGet(...args)
But React/Redux needs to go through that entire flow before you can use the new data.
This is where the componentDidUpdate() event comes in-handy because you can write logic when the component is re-rendered by new props or state.
Something like this would totally work:
componentDidUpdate(prevProps){
if(prevProps.SignUpUsers.length !== this.props.SignUpUsers.length){
//execute action
this.props.SignUpCheck(this.props.SignUpUsers)
}
}
For that I would suggest you take a look at redux-thunk middleware.
Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.
And based on your example, the code will end up like this:
<TouchableOpacity
onPress={() => this.props.uploadSignUpUsers(SignUpName, SignUpDesignation, SignUpEmail, SignUpMobileNo)}>
<Text>Upload</Text>
</TouchableOpacity>
const mapStateToProps = (state) => {
const { Auth: { SignUpUsers } } = state;
return { SignUpUsers };
}
Actions:
export const SIGN_UP_GET_USER_INFO_SUCCESS = "SIGN_UP_GET_USER_INFO_SUCCESS";
export const SIGN_UP_UPLOAD_SUCCESS = "SIGN_UP_UPLOAD_SUCCESS";
export const uploadSignUpUsers = (SignUpName, SignUpDesignation, SignUpEmail, SignUpMobileNo) => {
return async (dispatch, getState) => {
// here you can make the api call or any other async calculations
const { data: AuthUserInfo, error } = await api.post(SignUpName, SignUpDesignation, SignUpEmail, SignUpMobileNo);
dispatch({
type: SIGN_UP_GET_USER_INFO_SUCCESS,
payloadName: AuthUserInfo.SignUpName,
payloadDesignation: AuthUserInfo.SignUpDesignation,
payloadEmail: AuthUserInfo.SignUpEmail,
payloadMobile: AuthUserInfo.SignUpMobileNo,
});
const { Auth: { SignUpUsers } } = getState()
// and now you can upload your SignUpUsers
const { data: uploadData, error } = await.api.post(SignUpUsers)
dispatch({
type: SIGN_UP_UPLOAD_SUCCESS,
...uploadData // spread upload data to make it available in reducers
});
}
}
Reducer:
const INITIAL_STATE = { SignUpUsers: [] }
case SIGN_UP_GET_USER_INFO_SUCCESS: {
const { payloadName, payloadDesignation, payloadEmail, payloadMobile } = actions
return {
...state,
SignUpUsers: [ ...state.SignUpUsers, {
member_name: payloadName,
designation: payloadDesignation,
email: payloadEmail,
mobile_number: payloadMobile
}]
}
}
I'm getting the error:
Actions must be plain objects. Use custom middleware for async actions.
I've tried the solution in the following Stack Overflow question, but it didn't work:
React-Redux: Actions must be plain objects. Use custom middleware for async actions
action
export async function signupp(data){
console.log('In signupp:');
try{
const request = await axios({
method:'POST',
url:'http://192.168.1.10:3003/users/signup',
data:{
email:data.email,
password:data.password
},
}).then(response=>{
console.log(response.data);
return response.data
}).catch( e => {
console.log(e);
return false
});
return {
type:'signup',
payload:request
}
}
catch(e) {
console.log(e);
return false;
}
}
reducer
export default function(state={},action){
switch(action.type){
case 'signup':
return {
...state,
auth:{
email: action.payload.email,
password:action.payload.password
}
}
}
}
store
const createStoreWithMiddleware = applyMiddleware()(createStore);
const appRedux = () => (
<Provider store = {createStoreWithMiddleware(reducers)}>
<App/>
</Provider>
)
AppRegistry.registerComponent(appName, () => appRedux);
BTW, I am getting the right response in the log.
Inside of the component, in the place where you call signupp function, you have mapDispatchToProps function as callback in connect function from react-redux lib, which is doing behind the hoods something like dispatch(signupp())(or maybe you are doing dispatch directly without react-redux lib).
According to redux API, this dispatch function expects to receive a plain object, but your signupp() function returns a promise(as you have async inside).
To solve this problem you can simply use redux-thunk middleware. Also you can see some examples in the redux docs section about async actions.
An alternative solution could be to move fetch logic to component and then dispatch just plain object with data that you received from the request.
I have a number of actions and reducers setup for different content types, e.g. pages, events and venues. These actions and reducers get data which has been saved to AsyncStorage, by another action called sync, and puts it into the store.
Sync performs an async call to Contentful and retrieves any new/updated/deleted entries, which I then save to AsyncStorage.
What is the best way to ensure the view correctly is re-rendered after the async call is finished?
Should syncReducer merge data into the store that would normally be pulled out by pagesReducer, venuesReducer etc or should there be some kind of event emitted after syncReducer is done?
Data is pulled in asynchronously for offline viewing and keeping things fast, so I really don't want to wait for the sync before rendering.
data/sync.js
import { AsyncStorage } from 'react-native';
import database from './database';
const cache = {
getByType: async (query) => {
return new Promise(async(resolve, reject) => {
// Get results from AsyncStorage
resolve(results);
});
},
sync: async () => {
return new Promise(async(resolve, reject) => {
database
.sync(options)
.then(async results => {
// Save results to AsyncStorage
resolve(results);
});
});
}
};
export default cache;
actions/sync.js
import actionTypes from '../constants/actionTypes';
import cache from '../data/cache';
export function sync() {
return dispatch => {
dispatch(syncRequestedAction());
return cache
.sync()
.then(() => {
dispatch(syncFulfilledAction());
})
.catch(error => {
console.log(error);
dispatch(syncRejectedAction());
});
};
}
function syncRequestedAction() {
return {
type: actionTypes.SyncRequested
};
}
function syncRejectedAction() {
return {
type: actionTypes.SyncRejected
};
}
function syncFulfilledAction(data) {
return {
type: actionTypes.SyncFulfilled,
data
};
}
actions/getPages.js
import actionTypes from '../constants/actionTypes';
import cache from '../data/cache';
export function getPages() {
return dispatch => {
dispatch(getPagesRequestedAction());
return cache
.getByType('page')
.then(results => {
dispatch(getPagesFulfilledAction(results));
})
.catch(error => {
console.log(error);
dispatch(getPagesRejectedAction());
});
};
}
function getPagesRequestedAction() {
return {
type: actionTypes.GetPagesRequested
};
}
function getPagesRejectedAction() {
return {
type: actionTypes.GetPagesRejected
};
}
function getPagesFulfilledAction(settings) {
return {
type: actionTypes.GetPagesFulfilled,
pages
};
}
reducers/pagesReducer.js
import { merge } from 'lodash';
import actionTypes from '../constants/actionTypes';
const pagesReducer = (state = {}, action) => {
switch (action.type) {
case actionTypes.GetPagesRequested: {
return merge({}, state, { loading: true });
}
case actionTypes.GetPagesRejected: {
return merge({}, state, { error: 'Error getting pages', loading: false });
}
case actionTypes.GetPagesFulfilled: {
const merged = merge({}, state, { error: false, loading: false });
return { ...merged, data: action.pages };
}
default:
return state;
}
};
export default pagesReducer;
In the end I was able to solve this by importing the other actions into my sync action, and dispatching depending on which data needs to be updated.
import { getEvents } from './getEvents';
import { getPages } from './getPages';
import { getVenues } from './getVenues';
export function sync() {
return dispatch => {
dispatch(syncRequestedAction());
return cache
.sync()
.then(results => {
dispatch(syncFulfilledAction());
if (results.includes('event')) {
dispatch(getEvents());
}
if (results.includes('page')) {
dispatch(getPages());
}
if (results.includes('venue')) {
dispatch(getSettings());
}
})
.catch(error => {
console.log(error);
dispatch(syncRejectedAction());
});
};
}
Your sync action should be a thunk function (redux middleware) that makes the call to Contentful, resolves the promise, and contains the data, or error. Then you can dispatch another action, or actions to reduce the data into the store.
On each component that you want to re-render (based on the data being updated in the store via the actions we just dispatched and reduced), if you have connect(mapStateToProps, mapDispatchToProps) and have included those parts of the store in MSTP, those props will be updated which will re-render the components.
You can even be more explicit about the resolution of data if necessary by creating another action where you can dispatch and reduce to some part of your store the current state of the fetch.
So when you make the call, you could dispatch 'FETCH_IN_PROGRESS', then either 'FETCH_ERROR' or 'FETCH_SUCCESS' and if that was mapStateToProps into your component, you could choose to evaluate it in shouldComponentUpdate() and based on where in the process it is, you could either return true or false based on if you wanted to rerender. You could also force render in componentWillReceiveProps. I'd start with just relying on props changing and adding this if necessary.
You should use Redux Persist for this kind of thing, it supports AsyncStorage and a range of other options.
https://github.com/rt2zz/redux-persist
Actions and Reducers should be just designed to update the Redux store. Any other action is known as a side effect, and should be managed in a Middleware or Store Enhancer.
I would strongly advise against using Redux-Thunk it is way too powerful for the few things that it is useful for and very easy to create unmaintainable anti-patten code as it blurs the boundaries between actions and middleware code.
If you think you need to use Redux-Thunk first look to see if their is already a middleware that does what you need and if not learn about Redux-Sagas.
I'm trying to call dispatch in a non-component file.
My issue is that I'm trying to use redux-saga, but it is not letting me use the yield keyword inside of a callback function that I have to define:
peerConnection.onicecandidate = (event) => {
if (event.candidate) {
yield put({ type: videoSessionActions.SEND_LOCAL_CANDIDATE, payload: event.candidate });
}
}
So what I want to do instead is using plain old dispatch like so:
peerConnection.onicecandidate = (event) => {
if (event.candidate) {
dispatch({ type: videoSessionActions.SEND_LOCAL_CANDIDATE, payload: event.candidate })
}
}
Is there a way to import { dispatch } from 'redux'; ?
BTW this is all happening in my generator function in my saga. The reason I am not using redux-observable is because that requires react native v0.40.0+ which I can't update yet
Sure, there are many ways to go about doing this, in this issue you can see how.
The main thing you have to do is connect your component to the store like this:
export default connect()(Controls); You may also provide a first argument to the connect function which will be the mapStateToProps function. If you do this, you will be able to do something like this outside your component (Globally)
let createHandlers = function(dispatch) {
let peerConnection.onicecandidate = function(event) {
if (event.candidate) {
dispatch({ type: videoSessionActions.SEND_LOCAL_CANDIDATE, payload: event.candidate })
};
}
return {
peerConnection.onicecandidate,
// other handlers
};
}
Cheers!
I have this on the bottom of my main file:
export default connect(state => ({
state: state.firebaseReducer
}),
(dispatch) => ({
actions: bindActionCreators(firebaseActions, dispatch)
})
)(Routing);
And this is my reducer that I imported
const initialState = null;
export function firebaseRef(state = initialState, action) {
switch (action.type) {
case 'FIREBASE_REF_SET':
return action.value;
default:
return state;
}
}
Action:
export function setFirebaseRef(ref) {
return {
type: 'FIREBASE_REF_SET',
value: ref
};
}
But when I try to do this in my main file:
componentDidMount() {
state.setFirebaseRef(ref);
}
It says "Can't find variable: state" . Am I calling it the wrong way? I want to be able to call the setFireBaseRef action.
connect injects parts of state and dispatch into props. You want to dispatch the action using:
this.props.dispatch(setFireBaseRef(ref))
Or, assuming firebaseActionscontains setFireBaseRef, you can just do:
this.props.actions.setFireBaseRef(ref)