I am using redux in a phaser and react based game, dispatching actions in React Components, Utils, and Axios API Calls. I know there are useDispatch hook and connect can be used for React Components, however, based on my own experience, I can use dispatch from store directly as well.
import store from 'my-redux/store';
const { dispatch } = store;
dispatch(actionCreator(1));
I use the above way to dispatch actions in Phaser Scene and Utils to change states such as health and score, and dispatch actions in Axios async API calls. It is convenient and light compare to using useDispatch or connect, so why is it not recommended to dispatch from store except for isomorphic app?
Reference for why not use dispatch from store for isomorphic apps:
redux issue!916
redux issue!184
redux issue!362
I even want to bind dispatch to action creators like this:
import store from 'my-redux/store';
const { dispatch } = store;
export const handleSetSomeThing = (state) => {
const action = {
type: ActionTypes.SOME_TYPE,
payload: state,
};
dispatch(action);
};
Then I can call the above function like this without importing store or using connect, redux hook:
handleSetSomeThing({ health: 5 })
Any idea?
Related
I am using redux, react-redux and redux thunk for store management in my react native project, there is deferent reducers and actions. How I reset the entire store during logout
Is there any methods like createStore() to destroy a store?
please share possible solutions
Thanks
The below solution worked for me,
import reduxReset from 'redux-reset'
const enHanceCreateStore = compose(
applyMiddleware(thunk),
reduxReset()
)(createStore)
const store = enHanceCreateStore(reducers)
dispatch reset action
store.dispatch({
type: 'RESET'
})
I just started using redux, and I'm trying to fetch some data from Firebase and put it in my store. I did some research into the matter and it looked like to me that this:
export const addData = (database) => {
return dispatch => database.ref.once('value').then((snapshot) => {
dispatch({
type: 'STORE_DATA',
payload: snapshot.val()
});
}, (err) => {
dispatch(
{type: 'STORE_FAILED'})
})
}
should work, however I am getting an error "Error: Actions must be plain objects. Use custom middleware for async actions" when I call
store.dispatch(addData(firebase.database()))
I'm not sure what I'm doing wrong.
You need to use a custom middleware like redux thunk or sagas in order to create an action as a function instead of a plain object.
npm i redux-thunk
Then import this into the file where your store is located.
import thunk from 'redux-thunk'
And add it as an argument to your applyMiddleware function and applyMiddleware as an argument to your createStore function.
const store = createStore(rootReducer,
applyMiddleware(
thunk
)
);
This should give you the ability to run your async function inside your action.
I want to use nextjs in my new project with redux and thunk also. I wondering how to implement all packages correctly.
In my previous projects pages has HOC components like:
import {connect} from 'react-redux';
import Page from './about';
import {fetchUsers} from '../../actions/user';
const mapStateToProps = (state) => {
const {users} = state;
return users;
};
const mapDispatchToProps = (dispatch) => {
return {
fetchUsers: () => dispatch(fetchUsers())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Page);
And method to fetch users I implemented in componentDidMount
How to implement the same logic for nexjs?
What have I do?
Implemented store (base on next-redux-wrapper in _app.js)
Created HOC component (like below) with mapStateToProps and
mapDispatchToProps
Currently I thinking about use somehow this.props.fetchUsers method into getInitialProps - documentation say that this method should be used to fetch data before render site.
Please help me with correctly redux implementation for nextjs
You can follow this example
The correct way is to pass the store to the getInitialProps context and to the App component so you can pass it to the Provider.
The getInitialProps can't access to instance of the component, this is not accessible, so you can't call this.props.fetchUsers, but, because you are passing store to its context, you can do store.dispatch(fetchUsers()) and remove dispatch from mapDispatchToProps.
Generally I dispatch actions in getInitialProps and then map state to props within connect.
I am new to React with Redux structure and its concept. In my application, I need to navigate specific path in an action after login. My action code is:
const login = (resp:Object) => (dispatch: any) =>{
// api call
if(apiCall is success){
window.location.href = "http://localhost:3000"+localStorage.getItem("pathBeforeLogin");
}
else{
window.location.href = "http://localhost:3000/login";
}
});
}
This code is working fine but my senior asked me to do this work without using window.location.href. As We are using the react-router v4, browserHistory.push is also not working.
react-router-redux provides a Redux middleware that allow you to navigate via Redux actions.
From https://github.com/reactjs/react-router-redux:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { routerMiddleware, push } from 'react-router-redux';
// Apply the middleware to the store
const middleware = routerMiddleware(browserHistory);
const store = createStore(
reducers,
applyMiddleware(middleware)
);
// Dispatch from anywhere like normal.
store.dispatch(push('/foo'));
So in your example, instead of assigning strings to window.location.href, you'd do the following:
store.dispatch(push('/login'));
So i'm writing a React-Redux web app, and i call dispatch from my react components like this :
this.props.dispatch(someAction());
Now i need to call dispatch from a javascript function that is not a React Component, so how do i import the dispatch function and use it in this case ?
Thank you.
The dispatch function is a member of your redux store. If you created and exported your store in a module, it would be as easy as importing the store in your module and calling the dispatch function.
Example:
// store.js
import { createStore } from 'redux'
export default createStore(reducers)
// somefile.js
import store from './store'
store.dispatch(someAction)
The dispatch method is one of the store's methods. react-redux makes dispatch available to components as props via the provider, and mapDispatchToProps.
You can dispatch directly from the store:
store.dispatch(action)