How to Dispatch action on Enter #319
Comments
You can use a higher order function to get state into your onEnter hooks: <Route path='/' component={App} onEnter={requireAuth(store)}> And that hook might look something like: function requireAuth(store) {
return (nextState, replace) => {
let { auth } = store.getState();
if (!auth || !auth.loggedIn)
replace({ pathname: loginPath, query: { return_to: nextState.location.pathname } });
};
} Or something to that effect. |
This suggestion doesn't work with async actions |
Yes, it does. You need to take in the 3rd argument to the hook function so you have a |
Can you explain on example below, please? const LOAD_WAITING = 'PROJECT@LOAD_WAITING';
const LOAD_SUCCESS = 'PROJECT@LOAD_SUCCESS';
const LOAD_FAIL = 'PROJECT@LOAD_FAIL';
const initialState = {
waiting: false,
data: {},
fail: false
};
export default function reducer (state = initialState, action = {}) {
switch (action.type) {
case LOAD_WAITING:
return {...state, waiting: true, error: false};
break;
case LOAD_SUCCESS:
return {...state, waiting: false, data: action.result, error: false};
break;
case LOAD_FAIL:
return {...state, waiting: false, error: true};
break;
default:
return state;
}
}
//this is async action that handles by some middleware
function loadProject (id) {
return {
types: [LOAD_WAITING, LOAD_SUCCESS, LOAD_FAIL],
promise: request => request(`/api/project/${id}`).get({})
}
} In usual way inside my container i @connect(state => ({
project: state.project
}))
export default class Project extends Component {
//... component body
render () {
const {project} = this.props;
//there the project data is accessibile, of course
return (
<div>
Some markup
</div>
);
}
} But does it exist normal way to dispatch this async action inside import {loadProject} from './redux/project';
function load (store, dispatch) {
return function (nextState, replace, next) {
// how to dispatch(loadProject(nextState.params.id))
// and execute next() in the end of this async operation?
}
}
export function getRoutes (store, dispatch) {
return (
<Router>
<Route path="/" component={App}>
<Route path="/project/:id/" component={Project} onEnter={load(store, dispatch)}/>
</Route>
</Router>
);
} |
You need some sort of middleware in your redux store that can take in a Promise and return it, so you can chain on a I assume this is to preload your data, correct? I've found it's actually better to make that a static prop on your component that can do whatever actions will trigger the data to load. You can read that on the server side inside of your |
Thanx for reply, function load (store, dispatch) {
return function (nextState, replace, next) {
dispatch(loadProject(nextState.params.id)).then(data => {
//some code
next();
});
} |
Hi,
thanks for this great lib...
i'm missing some doc about how to use your redux store to do some things with the locations.
like :
The text was updated successfully, but these errors were encountered: