I am working on a project and still learning React. So currently, I have the following in my function. I was told that having numerous dispatches like so can cause problems, apart from looking messy and was suggested to create a single dispatch. How would I go about doing that?
dispatch({
type: 'UPDATE_ARRAY',
orderItemsArray: newitemsArray,
});
dispatch({
type: 'UPDATE_NUMBER',
tickNumber: tickNumber,
});
dispatch({
type: 'UPDATE_MESSAGE',
message: orderMessage,
})
Use redux-batched-actions.
const mapDispatchToProps = (dispatch) => ({
action2: id => dispatch(Actions.action2(id)),
action3: id => dispatch(Actions.action3(id)),
action1: (dateId, attrId) =>
dispatch(batchActions([
Actions.action2(dateId),
Actions.action3(attrId)
]))
});
When used out of the box without any performance optimisations, there are two primary concerns:
React will re-render multiple times
React Redux will re-evaluate selectors multiple times
Calling dispatch on forEach should work.
const actions = [{
type: 'UPDATE_ARRAY',
orderItemsArray: newitemsArray,
},{
type: 'UPDATE_NUMBER',
tickNumber: tickNumber,
},{
type: 'UPDATE_MESSAGE',
message: orderMessage,
}]
actions.forEach(action => dispatch(action));
What is the proper way to dispatch operationReset() inside of redux-observable epic?
Should I import actual store and use it?
It used to be like this, but following store is deprecated, and will be removed
// show operation failed message
(action$, store) => action$.ofType(OPERATION_FAILURE).map(() => (error({
title: 'Operation Failed',
message: 'Opps! It didn\'t go through.',
action: {
label: 'Try Again',
autoDismiss: 0,
callback: () => store.dispatch(operationReset())
}
}))),
This probably raises a larger question about how one should do notifications with callbacks, since it means you're sending a non-JSON serializable function as part of an action.
I'll assume you want to match the react notification system still. There's a way you can do this using Observable.create:
(action$, store) =>
action$.pipe(
ofType(OPERATION_FAILURE),
mergeMap(() =>
Observable.create(observer => {
observer.next(
error({
title: "Operation Failed",
message: "Oops! It didn't go through.",
action: {
label: "Try Again",
autoDismiss: 0,
callback: () => {
// Send off a reset action
observer.next(operationReset());
// Close off this observable
observer.complete();
},
// If the notification is dismissed separately (can they click an x?)
onRemove: () => observer.complete()
}
})
);
})
)
);
NOTE: I still wouldn't want to send callbacks as part of actions. Amusingly, one of my projects uses that notification system component too -- we have epics that will add notifications and clear them based on actions. All actions stay pure, and the notification system is a controlled side effect.
I have created a react-redux application. Currently what it does is load courses from the server(api), and displays them to the course component. This works perfectly. I'm trying to add a feature where you can create a course by posting it to the server, the server would then true an a success object. However, when i post to the server i get the following error(see below). I think this is due to my connect statement listening for the load courses action. Clearly its thinking it should be getting a list of something, instead of a success object. I have tried a few thing for it to listen for both courses and the success response, but to save you the time of reading all the strange thing i have done, i could not get it to work. Dose anyone know how to fix this issue ?
error
TypeError: this.props.courses.map is not a function
course.component.js
onSave(){
// this.props.createCourse(this.state.course);
this.props.actions.createCourse(this.state.course);
}
render() {
return (
<div>
<div className="row">
<h2>Couses</h2>
{this.props.courses.map(this.courseRow)}
<input
type="text"
onChange={this.onTitleChange}
value={this.state.course.title} />
<input
type="submit"
onClick={this.onSave}
value="Save" />
</div>
</div>
);
}
}
// Error occurs here
function mapStateToProps(state, ownProps) {
return {
courses: state.courses
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Course);
course.actions.js
export function loadCourse(response) {
return {
type: REQUEST_POSTS,
response
};
}
export function fetchCourses() {
return dispatch => {
return fetch('http://localhost:3000/api/test')
.then(data => data.json())
.then(data => {
dispatch(loadCourse(data));
}).catch(error => {
throw (error);
});
};
}
export function createCourse(response) {
return dispatch => {
return fetch('http://localhost:3000/api/json', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
response: response
})
})
.then(data => data.json())
.then(data => {
dispatch(loadCourse(data));
}).catch(error => {
throw (error);
});
};
}
course.reducer.js
export default function courseReducer(state = [], action) {
switch (action.type) {
case 'REQUEST_POSTS':
return action.response;
default:
return state;
}
}
server.js
router.get('/test', function(req, res, next) {
res.json(courses);
});
router.post('/json', function(req, res, next) {
console.log(req.body);
res.json({response: 200});
});
i have tried added a response to the state, and listening for it in the map state to props, but still for some reason react is trying to map response to courses. Do i need a second connect method?
function mapStateToProps(state, ownProps) {
return {
courses: state.courses,
resposne: state.resposne
};
}
As you can see from the pictures response is getting mapped as courses and not as response.
Picture
Assumptions:
state.courses is initially an empty array - from course.reducer.js
You don't call fetchCourses() action the first time you are rendering your view
Even if you call fetchCourses() there is no problem as long as courses in server.js is an array (the array in the response replaces the initial state.courses)
Flow:
Now I assume the first render is successful and React displays the <input type="text"> and submit button. Now when you enter the title and click on the submit button, the onSave() method triggers the createCourse() action with parameter that is more or less similar to { title: 'something' }.
Then you serialize the above mentioned param and send to the server (in course.actions.js -> createCourse()) which in turn returns a response that looks like {response: 200} (in server.js). Response field is an integer and not an array! Going further you call loadCourses() with the object {response: 200} which triggers the courseReducer in course.reducer.js
The courseReducer() replaces state.courses (which is [] acc. to assumption) with an integer. And this state update triggers a re-render and you end up calling map() on an integer and not on an array, thus resulting in TypeError: this.props.courses.map is not a function.
Possible Solution:
Return a valid response from serve.js (i.e. return the course object the endpoint is called with), or
Update your reducer to add the new course object into the existing state.courses array, like, return [...state, action.response]
Update:
Based on OP's comment, if what you want to do is send the new course object to the server, validate it and send success (or error) and based on response add the same course object to the previous list of courses, then you can simply call loadData() with the same course object you called createCourse() with and (as mentioned above) inside your reducer, instead of replacing or mutating the old array create a new array and append the course object to it, in es6 you can do something like, return [...state, course].
Update 2:
I suggest you go through Redux's Doc. Quoting from Redux Actions' Doc
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store.
The createCourse() action is called with a payload which is more-or-less like,
{title: 'Thing you entered in Text Field'}, then you call your server with an AJAX-request and pass the payload to the server, which then validates the payload and sends a success (or error) response based on your logic. The server response looks like, {response: 200}. This is end of the createCourse()action. Now you dispatch() loadCourses() action from within createCorse(), with the response you received from the server, which is not what you want (based on your comments). So, instead try dispatch()ing the action like this (try renaming response param, it's a bit confusing)
//.....
.then(data => {
dispatch(loadCourse(response)); // the same payload you called createCourse with
})
//.....
Now, loadCourse() is a very basic action and it simply forwards the arguments, which Redux uses to call your reducer. Now, in case you followed the previous discussion and updates how you call loadCourse(), then the return from loadCourse() looks like
{
type: REQUEST_POSTS,
response: {
title: 'Thing you entered in Text Field',
}
}
which is then passed onto your reducer, specifically your courseReducer().
Again quoting from Redux Reducers' Doc
Actions describe the fact that something happened, but don't specify how the application's state changes in response. This is the job of reducers.
The reducer must define the logic on how the action should impact the data inside the store.
In your courseReducer(), you simply returns the response field inside the action object and [expect] Redux to auto-magically mutate your state! Unfortunately this is not what happens :(
Whatever you return from the reducer, completely replaces whatever thing/object was there before, like, if your state looks like this
{ courses: [{...}, {...}, {...}] }
and you return something like this from your reducer
{ title: 'Thing you entered in Text Field'}
then redux will update the state to look like
{ courses: { title: 'Thing you entered in Text Field'} }
state.courses is no longer an Array!
Solution:
Change your reducer to something like this
export default function courseReducer(state = [], action) {
switch (action.type) {
case 'REQUEST_POSTS':
return [...state, action.response]
default:
return state
}
}
Side Note: This is may be confusing at times, so just for the sake of record, state inside courseReducer() is not the complete state but a property on the state that the reducer manages. You can read more about this here
--Edit after reading a comment of you in a different answer, I've scraped my previous answer--
What you're currently doing with your actions and reducers, is that you're calling loadCourse when you fetched the initial courses. And when you created a new course, you call loadCourse too.
In your reducer you're directly returning the response of your API call. So when you fetch all the courses, you get a whole list of all your courses. But if you create a new one you currently receive an object saying response: 200. Objects don't have the map function, which explains your error.
I would suggest to use res.status(200).json() on your API and switching the response status in your front-end (or using then and catch if you can validate the response status, axios has this functionality (validateStatus)).
Next I would create a separate action-type for creating posts and dispatch that whenever it's successful.
I would change your reducer to something like
let initialState = {
courses: [],
createdCourse: {},
}
export default (state = initialState, action) => {
switch (action.type) {
case 'REQUEST_POSTS':
return {
...state,
courses: action.response
}
case 'CREATE_COURSE_SUCCESS':
return {
...state,
createdCourse: action.response,
}
default: return state;
}
}
I wouldn't mind looking into your project and giving you some feedback on how to improve some things (ES6'ing, best practices, general stuff)
Based on the questions & answers so far, it looks like you need to do something like this:
1) Add a new action and dispatch this from your createCourse function
export function courseAdded(course, response) {
return {
type: 'COURSE_ADDED',
course
response
};
}
export function createCourse(course) {
return dispatch => {
return fetch('http://localhost:3000/api/json', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
course
})
})
.then(response => response.json())
.then(response => {
dispatch(courseAdded(course, response));
}).catch(error => {
throw (error);
});
};
}
2) Change your reducers to handle both fetching courses and adding a new course (we're using combineReducers to handle this here)
import { combineReducers } from "redux";
function response(state = null, action) {
switch (action.type) {
case 'COURSE_ADDED':
return action.response;
default:
return state;
}
}
function courses(state = [], action) {
switch (action.type) {
case 'COURSE_ADDED':
return [...state, action.course];
case 'REQUEST_POSTS':
return action.response;
default:
return state;
}
}
export default combineReducers({
courses,
response
});
3) Hook up to the new response state in your connect component
function mapStateToProps(state, ownProps) {
return {
courses: state.courses,
response: state.response
};
}
4) Do something with this new response prop in your component if you want to show it e.g.
// this is assuming response is a string
<span className="create-course-response">
Create Course Response - {this.props.response}
</span>
UPDATE
I've added support for adding the new course to the end of the existing course list, as well as handling the response. How you shape the state is completely up to you and it can be re-jigged accordingly.
In order for this code to work, you will need to add support for the spread operator. If you are using babel it can be done like this. Creating a new object is important to ensure that you don't mutate the existing state. It will also mean react-redux knows the state has changed. Spread operator isn't essential and this can be done with Object.assign, but that syntax is ugly IMO.
I'm trying to create an epic that will take an action, and then dispatch two different actions, with the second one delayed by two seconds. After a bunch of attempts, this was the best I could do:
const succeedEpic = action$ =>
action$.filter(action => action.type === 'FETCH_WILL_SUCCEED')
.mapTo({ type: 'FETCH_REQUEST' })
.merge(Observable.of({ type: 'FETCH_SUCCESS' }).delay(2000))
Unfortunately, it seems that:
Observable.of({ type: 'FETCH_SUCCESS' }).delay(2000)
Is run immediately upon my app being loaded (rather than when an event comes down the parent stream). I noticed this because the FETCH_SUCCESS action is received by the reducer exactly two seconds after my app is loaded. I even attached a console.log to confirm this:
const succeedEpic = action$ =>
action$.filter(action => action.type === 'FETCH_WILL_SUCCEED')
.mapTo({ type: 'FETCH_REQUEST' })
.merge(Observable.of({ type: 'FETCH_SUCCESS' })
.do(() => console.log('this has begun'))
.delay(2000)
)
"this has begun" is logged to the console the moment the app is started.
I suspect this has something to do with how Redux-Observable automatically subscribes for you.
The desired behaviour is that I will:
Click a button that dispatches the FETCH_WILL_SUCCEED event.
Immediately, a FETCH_REQUEST event is dispatched.
Two seconds after that, a FETCH_SUCCESS event is dispatched.
It turns out I needed to wrap both of my events inside a mergeMap. Thanks to #dorus on the RxJS Gitter channel for this answer.
This is my working result:
const succeedEpic = action$ =>
action$.filter(action => action.type === 'FETCH_WILL_SUCCEED')
.mergeMapTo(Observable.of({ type: 'FETCH_REQUEST' })
.concat(Observable.of({ type: 'FETCH_SUCCESS' })
.delay(1000)))
merge should work as well in place of concat, but I thought concat makes better semantic sense.
There might be a more elegant solution, but why not just use 2 epics and combine them?
The first one dispatches the fetch request:
const onFetchWillSucceed = action$ => action$.ofType('FETCH_WILL_SUCCEED')
.mapTo({ type: 'FETCH_REQUEST' })
The second one waits 2 secs and dispatches the success:
const onFetchRequest = action$ => action$.ofType('FETCH_REQUEST')
.delay(2000)
.mapTo({ type: 'FETCH_SUCCESS' })
And in the end they are just combined into 1 epic
const both = combineEpics(onFetchWillSucceed, onFetchRequest)
I'm new to RxJS. In my app I need independent cancellation of deferred action. Here's a working example (the delay is 3 seconds). But when I choose to delete multiple items and cancel one of them, then canceled all at once.
Epic code:
const itemsEpic = action$ =>
action$.ofType('WILL_DELETE')
.flatMap(action =>
Observable.of({type: 'DELETE', id: action.id})
.delay(3000)
.takeUntil(action$.ofType('UNDO_DELETE'))
)
I think I need to pass an id to takeUntil operator, but I don't know how to do it.
If I understand the takeUntil operator correctly, it stops emitting new items from the Observable it was called on, once the argument Observable emits it's first item. With this in mind you could do something like this:
const itemsEpic = action$ => action$.ofType('WILL_DELETE')
.flatMap(action => Observable.of({ type: 'DELETE', id: action.id })
.delay(3000)
.takeUntil(action$.ofType('UNDO_DELETE').filter(({id}) => id === action.id))
)