I have created a thunk that dispatches a bunch of different actions:
export function resetEverything() {
return function (dispatch) {
return Promise.all([
dispatch(updateCurrentColor('blue')),
dispatch(updateCurrentTypeChoice('hot')),
dispatch(updateData('fish', {})),
dispatch(updateData('giraffes', {})),
dispatch(updateData('elephants', {})),
dispatch(updateData('zebras', {})),
]).then(() => console.log('resetEverything called'));
};
}
These actions are also used in the application individually. Individually called, they work fine; the store is updated with the payloads.
However, in this batch operation, all of the actions are dispatched, the console shows "resetEverything called", and even when I look through the Redux extension in Chrome, each of the actions are dispatched with the same structure (with different payload, naturally). But...when I look at the Diff it says (states are equal) and sure enough, examining the State>Tree shows that the store keys haven't been updated at all.
Why isn't this working? Why are the dispatched actions being ignored?
Reducer:
import update from 'immutability-helper';
function reducer(state = initialState, action = {}) {
switch (action.type) {
case UPDATE_CURRENT_COLOR:
return update(state, { currentColor: { $set: action.payload } });
case UPDATE_CURRENT_TYPE_CHOICE:
return update(state, { currentTypeChoice: { $set: action.payload } });
case UPDATE_DATA:
return update(state, { data: { [action.payload.property]: { $merge: action.payload.dataObject } } });
default: return state;
}
}
Related
I managed to write reducer using createSlice but the action seems to be confusing.
My old reducer :
function listPeopleReducer(state = {
getPeople:{}
}, action){
switch (action.type) {
case D.LIST_PEOPLE: {
return {
...state
, getPeople:action.payload
}
}
default:{}
}
return state
}
By using createSlice from the redux toolkit, I migrated the reducer to this,
const listPeopleReducer = createSlice({
initialState:{getPeople:{}},
name:"listPeople",
reducers:{
listPeople(state,action){
return {
...state,
getPeople : action.payload
}
}
}
})
My old action, makes an api call inside it, with the help of a helper function makeApiRequest (which takes in parameters and returns the response of the api),
export function listPeople(config: any) {
return function (dispatch: any) {
makeApiRequest(config)
.then((resp) => {
dispatch({
type : D.LIST_PEOPLE,
payload : resp.data
})
})
.catch((error) => {
dispatch({
type : D.LIST_PEOPLE,
payload : error
})
})
}
}
With reduxtool kit, we could do something like,
const listPeople = listPeopleReducer.actions.listPeople;
But, how will I write my custom action that contains the helper function makeApiRequest ?
i.e The old Action should be migrated to reduxtoolkit type.
It's definitely tricky when migrating, since there are some major conceptual changes that you must eventually wrap your head around. I had to do it a couple of times before it clicked.
First, when you are creating const listPeopleReducer with createSlice(), that is not actually what you are creating. A slice is a higher level object that can generate action creators and action types for you, and allows you to export reducers and actions FROM it.
Here are the changes I would make to your code:
const peopleSlice = createSlice({
initialState:{getPeople:{}},
name:"people",
reducers:{
listPeople(state,action){
// uses immer under the hood so you can
// safely mutate state here
state.getPeople = action.payload
}
},
extraReducers:
// each thunk you create with `createAsyncThunk()` will
// automatically have: pending/fulfilled/rejected action types
// and you can listen for them here
builder =>
builder.addCase(listPeople.pending, (state,action) => {
// e.g. state.isFetching = true
})
builder.addCase(listPeople.fulfilled, (state,action) => {
// e.g. state.isFetching = false
// result will be in action.payload
})
builder.addCase(listPeople.rejected, (state,action) => {
// e.g. state.isFetching = false
// error will be in action.payload
})
}
})
Then, outside of your slice definition, you can create actions by using createAsyncThunk(), and do like:
export const listPeople = createAsyncThunk(
`people/list`,
async (config, thunkAPI) => {
try {
return makeApiRequest(config)
} catch(error) {
return thunkAPI.rejectWithError(error)
// thunkAPI has access to state and includes
// helper functions like this one
}
}
}
The "Modern Redux with Redux Toolkit" page in the Redux Fundamentals docs tutorial shows how to migrate from hand-written Redux logic to Redux Toolkit.
Your makeApiRequest function would likely be used with Redux Toolkit's createAsyncThunk, except that you should return the result and let createAsyncThunk dispatch the right actions instead of dispatching actions yourself.
I started using Redux with React. My Store contains several job Objects each with an id. I want to call a function, whenever I add/update a new Job. What's the recommended way to do so?
Here's my reducer
function reducer(state:= {}, action) {
const { id, fields } = action.payload
switch (action.type) {
case ADDED:
if (!state[id]) {
return {
...state,
[id]: fields,
},
};
} else {
const currentDate = moment(stat[id].lastModified)
const newDate = moment(fields.metaData.lastModified);
if (!currentDate.isSame(newDate)) {
return {
...state,
[id]: { ...state[id], ...fields },
},
};
}
// don't update otherwise
return state;
}
case OTHERS:
......
}
Whenever something is added, I add it to the state, if it already exists but the modificationDate is newer, I update it in the state. I want my function to the called in either ADDED cases
Reducers must do only state update (no more). It seems you need using Redux middleware for that
I have a use case like this:
eventListReducer: will get a list of events based on date range
eventDetailReducer: will get the event details based on one event id
I know how to do the two above, my question:
When my page loads initially, I will get a list of events based on default date range and load the first event details, I can certainly create an
EventListAndDetailReducer to duplicate eventListReducer and eventDetailReducer. Is there any better way I can reuse the logic?
What I want to achieve is to have another action, that will first call getEvents and update the eventLists state, and then grab the first event and call setEvent and update the eventDetail state.
This is my eventDetailReducer:
const initialState = {
eventDetails: "",
}
const eventReducer = (state = initialState, action) => {
switch (action.type) {
case "SET_EVENT":
state = {
...state,
eventDetails: action.payload
};
break;
}
return state;
}
export default eventReducer;
This is my eventsReducer:
const initialState = {
eventsList: [],
}
//getEventsReducer
const getEventsReducer = (state = initialState, action) => {
switch (action.type) {
case "GET_EVENTS":
state = {
...state,
eventList: ["Joe", "Tom", "Marry"] //assuming this from some other endpoint
};
break;
}
return state;
}
export default getEventsReducer;
What about using EventListAndDetailReducer?
const initialState = {
eventsList: [],
eventDetails: ""
}
export function eventListAndDetailReducer(state, action) {
switch(action.type) {
case GET_EVENTS:
return {...state, eventList: eventsReducer(state.eventsList, action)}
case "SET_EVENT":
return {...state, eventDetails: eventDetailsReducer(state.eventDetails, action)}
default:
return state
}
}
and then somewhen start using combineReducers?
Why not just have the eventDetails reducer also update on the GET_EVENTS action?
const eventReducer = (state = initialState, action) => {
switch (action.type) {
case "SET_EVENT":
state = {
...state,
eventDetails: action.payload
};
break;
case "GET_EVENTS":
state = {
...state,
eventDetails: action.payload[0] // assuming payload is an array
};
break;
}
return state;
}
Remember, all reducers receive all actions, so it does not need to be a 1-1 mapping.
What I understand from you question is that you want another action to do both actions sequentially and be dependent on each. I assume you have some middle ware such as redux-thunk that allows actions to be more than plaIn functions!
export function combinedAction() {
return (dispatch, getState) => {
// Write fetch() request to get events list from anywhere.
// Following should be within .then() if you're using fetch.
// Here events are just hardcoded in reducer!
dispatch(return { type: GET_EVENTS, payload: events }).then( () => {
let event = getState().eventsList[0]
dispatch(return { type: SET_EVENT, payload: event })
})
};
}
This will fire up GET_EVENTS action first and it'll set events array in state.eventsList. Then next action just uses this state information to dispatch next action SET_EVENT. Refer here to learn about chaining actions. How to chain async actions?
I've ran into this issue quite a few times where I want to access action.payload further down the chain. But by then, the argument passed to mergeMap has already changed to something else.
Given my action looks like this:
{
type: BUY_GEMS,
payload: { value: 123, productIdentifier: "ABC123" }
}
And this epic:
function purchaseGems(action$, store) {
return action$
.ofType(BUY_GEMS)
.mergeMap(action => {
const { productIdentifier } = action.payload; // <-------- works because it's the first mergeMap in this sequence
return Observable.fromPromise(
// Some promise call
).catch(error => Observable.of(buyGemsRejected(error)));
})
.mergeMap(action => {
const { value } = action.payload; // <----------- doesn't work because "action" is now just the response of the Promise above.
...
});
}
How would I do this?
This trick is to just place your second mergeMap inside the closure where the action is available. In fact, even if you didn't need access to it I generally recommend this pattern in redux-observable whereby you isolate your Observable chains inside your single top-level merging strategy operator (mergeMap, switchMap, etc) because it makes future refactoring like this easier as well as easier error isolation (if added).
function purchaseGems(action$, store) {
return action$
.ofType(BUY_GEMS)
.mergeMap(action => {
const { productIdentifier } = action.payload;
return Observable.fromPromise(somePromise)
.catch(error => Observable.of(buyGemsRejected(error)))
.mergeMap(response => {
const { value } = action.payload;
// ...
});
});
}
Your example contained Observable.fromPromise() which I assume is just pseudo code, so I followed suit with Observable.fromPromise(somePromise) for more clarity for other readers.
Recently I've been looking into react and redux. I read up the official documentation and tried some ToDo List tutorials. Part 1 is just about react and this is part 2 about redux:
http://www.theodo.fr/blog/2016/03/getting-started-with-react-redux-and-immutable-a-test-driven-tutorial-part-2/
So basically he just sets up a store and initially adds an array of a few todos. Now I don't want my data to be local and I want to fetch it from an API. I'm having a hard time understanding how this actually works. So the code I would use in my action_creators.js is:
export function fetchData() {
return dispatch => {
fetch('http://127.0.0.1:8000/example')
.then(res => res.json())
.then(res => dispatch({
type: FETCH_DATA,
data: res
}))
}
}
Now in the example code for example adding a 'todo':
export function addItem(text) {
return {
type: 'ADD_ITEM',
text
}
}
You aren't dispatching anything, the tutorial does this in the reducer? But when you return dispatch your fetch, does this automatically get dispatched to your store?
If so I have no clue what I should write in my reducer ..
This is the code I have for adding a 'todo':
import {Map} from 'immutable';
function setState(state, newState) {
return state.merge(newState);
}
function fetchData(state) {
return state;
}
function addItem(state, text) {
const itemId = state.get('hostnames').reduce((maxId, item) => Math.max(maxId,item.get('id')), 0) + 1;
const newItem = Map({id: itemId, text: text, status: 'active'});
return state.update('hostnames', (hostnames) => hostnames.push(newItem));
}
export default function(state = Map(), action) {
switch (action.type) {
case 'SET_STATE':
return setState(state, action.state);
case 'ADD_ITEM':
return addItem(state, action.text);
case 'FETCH_DATA':
return fetchData(state);
}
return state;
}
So basically my question is, how do I fetch the data ( if the fetch is wrong now ) and how do I add the fetched data from my api to the store in my reducer.
I just find react and redux pretty complicated so sorry if I'm asking a really noob question or just making big mistakes in the way I want to do something.
Thanks in advance for any help.
imagine your json
{
"data": {
"apple": 1,
"banana": 3,
},
"status": 200,
}
your actions
export function fetchData() {
return dispatch => {
fetch('http://127.0.0.1:8000/example')
.then(res => res.json())
.then((responseData) => {
if(responseData.status === 200){
dispatch(setData(responseData));
}
})
}
}
export function setData(responseData) {
return {type: SET_DATA, data: responseData.data }
}
your reducer
const initialState = { data: null };
export default function(state = initialState, action) {
switch (action.type) {
case 'SET_DATA':
return Object.assign({}, state, {
data: action.data,
})
default:
return state;
}
}
then your state will become
{ data: {
apple: 1,
banana: 3,
}
}
Actually, all your reducers should be pretty dumb and pure (without any side effects). So their only concern is to modify the state and nothing else. Fetching data from the server or any kind of orchestration should be implemented in redux middleware. Look at redux-thunk or redux-saga if you need something more complicated. Hope that helps.