Reputation: 63
I want to pass the the action data to the initial state and without having waiting for the data to be fetched.
I followed this tutorial and it works, but I'm trying to modify it to parse any JSON data and that works too but I keep having to enter a username to fetch the data and I wish it could get fetched from the initial state. Sorry if I didn't explain this right but I hope you get it.
const initialState = {
userData: {},
isFetching: false,
isError: false
};
const asyncReducer = (state = initialState, action) => {
switch (action.type) {
case "FETCH_USER":
return Object.assign({}, state, {
isFetching: true,
userData: {},
isError: false
});
case "FETCHED_USER":
return Object.assign({}, state, {
userData: action.data,
isFetching: false,
isError: false
});
case "RECEIVE_ERROR":
return Object.assign({}, state, {
isError: true,
isFetching: false
});
default:
return state;
}
};
export default asyncReducer;
Upvotes: 1
Views: 34
Reputation: 9065
Your question is a little unclear and with no action code to go by I think what you are saying is you want to access the redux store in your action creator so you don't have to fetch user data from you backend or wherever each time correct? If thats the case you can very simply add a second argument to thunk after dispatch and get the state. Then you will have the states value for you to modify against. So you could to something like the following in your action:
const myAction = () => (dispatch, getState) => {
const userData = getState().userData;
...do your stuff with that
dispatch({
type: "FETCHED_USER",
data: new_stuff
});
}
Upvotes: 1