I've got a parent component that has 2 child components;
UPDATE
I've rewritten some statements and code to make it more understandable.
Parent: ReservationFormComponent
Children: ReservationTypePanel & ReservationCalendarPanel
The parent component ReservationFormComponent initially displays the ReservationTypePanel only. The other sibling ReservationCalendarPanel is hidden until an item is selected on ReservationTypePanel.
So the problem is when an item is selected in ReservationTypePanel the ReservationCalendarPanel is rendered with initial values set in the ReservationFormStore store. Particularly
initialize: function(){
this.reservationType = void 8;
this.pickupTime = moment().add('minutes',30);
}
So when the ReservationCalendarPanel is rendered, its child Component DateTimeField which accepts the state pickupTime get re-rendered and fires up the onChange event which calls for another action
return DateTimeField({
pickupTime: pickupTime,
onChange: function(time){
// Here is where the action gets called again
this$.getFlux().actions.setReservationPickupTime(time);
}
});
And greets me with this error Uncaught Error: Cannot dispatch an action while another action is being dispatched
I've tried my best to trim down the codes below. I wasn't using JSX because the original code was in LiveScript so I just took the compiled code to display here instead.
This is the parent component ReservationFormComponent
ReservationFormComponent = React.createClass({
get flux(){ // Instantiating Fluxxor
return new Fluxxor.Flux({ // These are the stores
'reservation-form': new ReservationFormStore,
'reservation-types': new ReservationTypeStore
}, { // These are the actions
setReservationType: function(value){
return this.dispatch('SET_RESERVATION_TYPE', value);
},
setReservationPickupTime: function(value){
return this.dispatch('SET_RESERVATION_PICKUP_TIME', value);
}
});
},
componentWillMount: function(){
this.flux.store('reservation-form').addListener('change', this.onChange);
},
onChange: function(){ // This triggers the re-render to display the ReservationCalendarPanel
this.setState({
pickupTime: this.flux.store('reservation-form').pickupTime
});
},
render: function() {
reservationType = this.state.reservationType;
return form({
className: 'container'
}, ReservationTypePanel({
flux: this.flux
}), reservationType ? ReservationCalendarPanel({
flux: this.flux
}) : null // This conditional to mount or not mount the component
);
}
});
The ReservationTypePanel Component. Here, the rendered component listens to onClick event and dispatches setReservationType action.
ReservationTypePanel = React.createClass({
mixins: [fluxxor.FluxMixin(react)],
onSelectReservationType: function(reservationType){
var this$ = this;
return function(event){
this$.getFlux().actions.setReservationType(reservationType);
};
},
render: function() {
var this$ = this;
return ReservationTypeItem({
onClick: this$.onSelectReservationType(type);
})
}
});
The ReservationCalendarPanel Component. Here is where the DateTimeField is rendered and receives the state from the ReservationFormStore and sets the value which causes another dispatch. This is where the error comes.
ReservationCalendarPanel = React.createClass({
mixins: [fluxxor.FluxMixin(react)],
getInitialState: function() {
return {pickupTime: moment()} // sets the current time
},
componentWillMount: function(){
this.getFlux().store('reservation-form').addListener('change-pickup-time', this.onFlux);
},
componentWillUnmount: function(){
this.getFlux().store('reservation-form').removeListener('change-pickup-time', this.onFlux);
},
render: function() {
var this$ = this;
if (this.state.pickupTime) {
pickupTime = moment(this.state.pickupTime);
}
return DateTimeField({
date: pickupTime,
onChange: function(time){
// Here is where the action gets called again
this$.getFlux().actions.setReservationPickupTime(time);
}
});
});
This is the DateTimeField this is where the
DateTimeField = React.createClass({
getInitialState: function(){
return {
text: ''
};
},
componentWillReceiveProps: function(nextProps){
this.setDate(nextProps.date);
},
componentDidMount: function(){
$(this.getDOMNode()).datepicker()
.on('changeDate', this.onChangeDate)
.on('clearDate', this.onChangeDate);
this.setDate(this.props.date);
},
componentWillUnmount: function(){
return $(this.getDOMNode()).datepicker('remove');
},
getDatepickerDate: function(){
return $(this.getDOMNode()).datepicker('getDate');
},
setDate: function(date){
if (!this.isMounted()) {
return;
}
if (moment(date).isSame(this.getDatepickerDate, 'day')) {
// If there is no change between the date that
// is about to be set then just ignore and
// keep the old one.
return;
}
date = date ? moment(date).toDate() : void 8;
$(this.getDOMNode()).datepicker('setDate', date);
},
onChangeDate: function(event){
if (this.props.onChange) {
this.props.onChange(event.date);
}
},
render: function(){
return this.transferPropsTo(input({
type: 'text',
className: 'form-control'
}));
}
});
If in case here is the store:
ReservationFormStore = fluxxor.createStore({
actions: {
SET_RESERVATION_TYPE: 'setReservationType',
SET_RESERVATION_PICKUP_TIME: 'setPickupTime'
},
initialize: function(){
this.reservationType = void 8;
this.pickupTime = moment().add('minutes',30);
},
setReservationType: function(reservationType){
this.reservationType = reservationType;
this.reservationTypeValidate = true;
this.emit('change-reservation-type', this.reservationType);
this.emit('change');
}
setPickupTime: function(pickupTime){
this.pickupTime = pickupTime;
this.pickupTimeValidate = true;
this.emit('change-pickup-time', this.pickupTime);
this.emit('change');
}
});
Related
I am creating undo/redo functionality in VueJS. I watch the settings and add a new element to an array of changes when the settings change. I also have a method for undo when the undo button is clicked.
However, when the button is clicked and the last setting is reverted, the settings are changed and the watch is fired again.
How can I prevent a new element being added to the array of changes if the settings changed but it was because the Undo button was clicked?
(function () {
var Admin = {};
Admin.init = function () {
};
var appData = {
settings: {
has_border: true,
leave_reviews: true,
has_questions: true
},
mutations: [],
mutationIndex: null,
undoDisabled: true,
redoDisabled: true
};
var app = new Vue({
el: '#app',
data: appData,
methods: {
undo: function() {
if (this.mutations[this.mutationIndex - 1]) {
let settings = JSON.parse(this.mutations[this.mutationIndex - 1]);
this.settings = settings;
this.mutationIndex = this.mutations.length - 1;
console.log (settings);
}
},
redo: function() {
}
},
computed: {
border_class: {
get: function () {
return this.settings.has_border ? ' rp-pwb' : ''
}
},
undo_class: {
get: function () {
return this.undoDisabled ? ' disabled' : ''
}
},
redo_class: {
get: function () {
return this.redoDisabled ? ' disabled' : ''
}
}
},
watch: {
undoDisabled: function () {
return this.mutations.length;
},
redoDisabled: function () {
return this.mutations.length;
},
settings: {
handler: function () {
let mutation = JSON.stringify(this.settings),
prevMutation = JSON.stringify(this.mutations[this.mutations.length-1]);
if (mutation !== prevMutation) {
this.mutations.push(mutation);
this.mutationIndex = this.mutations.length - 1;
this.undoDisabled = false;
}
},
deep: true
}
}
});
Admin.init();
})();
Since you make the changes with a button click, you can create a method to achieve your goal instead of using watchers.
methods: {
settings() {
// call this method from undo and redo methods if the conditions are met.
// move the watcher code here.
}
}
BTW,
If you don't use setter in computed properties, you don't need getters, so that is enough:
border_class() {
return this.settings.has_border ? ' rp-pwb' : ''
},
These watchers codes look belong to computed:
undoDisabled() {
return this.mutations.length;
},
redoDisabled() {
return this.mutations.length;
},
I have a problem to find a way to easy get state value from component in other component. When I click on any tag.
I want to append value of tag to list state in Form component if tag is clicked. Is there any simply way to do this ?
I have component like this:
var Tag = React.createClass({
getInitialState: function(){
return {
checked: false
};
},
componentDidMount: function() {
this.setState({
checked: false
});
},
_onChange: function(event) {
if(this.state.checked == false){
this.setState({
checked: true
});
} else {
this.setState({
checked: false
});
}
},
render: function() {
return (
<div className="review-tag">
<input
type="checkbox"
id={this.props.id}
name={this.props.name}
checked={this.state.checked}
value={this.props.id}/>
<label htmlFor={this.props.name} onClick={this._onChange}>{this.props.name}</label>
</div>
);
return (
<div>
<span>{this.props.name}</span>
</div>
);
}
});
var allTags = tags;
var ReviewTag = React.createClass({
render: function() {
const tagComps = allTags.map(function(tag){
return <Tag {...tag}/>;
});
return (
<div>
{tagComps}
</div>
);
}
});
Tag component have included value at rendering and I have to get value of each tag in my ReviewForm component which looks like this:
var fd = new FormData();
var ReviewForm = React.createClass({
getInitialState: function(){
return {
Author: '',
Tags: ''
};
},
componentDidMount: function() {
this.setState({
Author: author,
Tags: tags
});
},
submit: function (e){
var self;
e.preventDefault();
self = this;
var data = {
tags: this.state.Tags,
author: this.state.Author
};
for (var key in data) {
fd.append(key, data[key]);
}
$.ajax({
type: 'POST',
url: '/reviews/submit/',
data: fd,
processData: false,
contentType: false
})
.done(function(data) {
console.log('Review added successfully.');
})
.error(function(msg) {
var errors = msg.responseJSON;
console.log(errors);
});
},
render: function() {
<div className="scolumn">
<ReviewTag/>
</div>
}
})
Many thanks for any help.
You don't need to set state in componentDidMount — remove that piece of code.
Really, couldn't all of that...
_onChange: function(event) {
if(this.state.checked == false){
this.setState({
checked: true
});
} else {
this.setState({
checked: false
});
}
},
be substituted with _onChange: function(event) { this.setState(checked: !this.state.cheked) }?
allTags should be passed as property, not as outer scope variable.
Now to your main question.
Move state to parent component (ReviewForm). You can have state as a hash with {name: isChecked} structure (name is Tag's name, and isChecked is boolean). Pass it down to ReviewTag and futher down to Tag as property. Also pass down your _onChange handler as property (it should be moved to parent component — ReviewForm — as well).
So when the Tag is checked, it calls ReviewForm's handler, and ReviewForm's handler changes its own state accordingly.
What's the best way to set state based on the data received from observe()?
It seems setting state via componentWillMount() won't work as observe() runs after this and the data isn't available to set state.
I'm using the observe function as advised when using Parse
E.g.:
var DragApp = React.createClass({
getInitialState: function () {
return {
activeCollection : ''
};
},
observe: function() {
return {
collections: (collectionsQuery.equalTo("createdBy", currentUser))
};
},
_setactiveCollection: function(collection) {
this.setState({
activeCollection : collection
});
},
componentWillMount: function () {
var collection = this.data.collections[0];
this._setActiveCollection(collection);
},
)}
I went the wrong way about this.
I shouldn't be storing this.data into state. I can pass it into components via render.
To get round this.data not being ready before rendering, I make use of the ParseReact function pendingQueries() inside render. E.g.
if (this.pendingQueries().length > 0) {
content = 'loading...'
} else {
content = 'hello world I am' + this.data.name
}
Try:
var DragApp = React.createClass({
observe: function() {
var collections = collectionsQuery.equalTo("createdBy", currentUser);
return {
collections: collections,
activeCollection: collections[0]
};
},
render: function () {
// do something with this.data.collections and/or this.data.activeCollection
},
)}
I'm having an issue with creating a component using react and martyjs. I'm sure it is a typo or something but I just can't seem to find it. Although I have a state mixin in the component the state is not being populated and it doesn't look like getState is even being called in the mixin.
Mixin.es6
var StateMixin = Marty.createStateMixin({
listenTo: VideoStore,
getState: function() {
return {
items: VideoStore.list(),
currentItem: VideoStore.select(),
}
}
});
State.es6
var VideoStore = Marty.createStore({
displayName: "Store",
handlers: {
list: Events.List,
render: Events.Render
},
getInitialState: function(){
return { };
},
list: function(){
return this.fetch({
id: 'list',
locally: function(){
if(this.hasAlreadyFetched('list') )
return this.state.items;
},
remotely: function(){
return DissolveStateSource.list();
}
});
},
select: function(){},
render: function(){}
});
Component.es6
$( ()=>
React.render(
<VideosTable/>,
$("#container")[0]
));
var VideosTable = React.createClass(
{
mixins: StateMixin,
render: function() {
var body = this.state.list.when({ //state is null here
pending: function(){
return <span className="ball"></span>;
},
failed: function(error){
return <div className="error">error.message</div>;
},
done: function(videos){
return <div>Videos</div>;
}
});
return <h2>hello</h2>;
}
});
Any idea what I'm doing wrong?
Edit: I've added a js bin thing here
http://jsbin.com/lekegicumo/2/edit?html,js,console,output
Looks like a typo in Mixin.es6 to me.
Change getState to getInitialState.
Also, in Component.es6:
Change mixins: StateMixin to mixins: [StateMixin].
The problem ended up being that the order of inclusion of JavaScript files was incorrect. Swapping some around fixed the issue.
are u using react v0.1.13.0
this is new way to initial your state using 'construct'
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html
I've created 2 separate views, 1 to render the template and the other one is where I bind the events, then I tried merging them into one in which case it causes an Uncaught TypeError: Object [object Object] has no method 'template'. It renders the template and the events are working as well, but I get the error.
edit.js, this is the combined view, which I think it has something to do with their el where the error is coming from
window.EditView = Backbone.View.extend ({
events: {
"click #btn-save" : "submit"
},
initialize: function() {
this.render();
},
render: function() {
$(this.el).html(this.template());
return this;
},
submit: function () {
console.log('editing');
$.ajax({ ... });
return false;
}
});
var editView = new EditView();
signin.js, this is the view that I can't merge because of the el being used by the ajax call and in SigninView's $(this.el) which causes the rendering of the templates faulty
window.toSigninView = Backbone.View.extend ({
el: '#signin-container',
events: {
"click #btn-signin" : "submit"
},
initialize: function() {
console.log('Signin View');
},
submit: function() {
$.ajax({ ... });
return false;
}
});
var toSignin = new toSigninView();
window.SigninView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
$(this.el).html(this.template());
return this;
}
});
and I use utils.js to call my templates
window.utils = {
loadTpl: function(views, callback) {
var deferreds = [];
$.each(views, function(index, view) {
if (window[view]) {
deferreds.push($.get('templates/' + view + '.html', function(data) {
window[view].prototype.template = _.template(data);
}));
} else {
alert(view + " not found");
}
});
$.when.apply(null, deferreds).done(callback);
}
};
In my Router.js, this is how I call the rendering of templates
editProfile: function() {
if (!this.editView) {
this.editView = new EditView();
}
$('#global-container').html(this.editView.el);
},
utils.loadTpl (['SigninView', 'EditView'],
function() {
appRouter = new AppRouter();
Backbone.history.start();
});
I think that I figured out your problem.
First merge your views and delete the line var toSignin = new toSigninView();
Second modify your utils.js code like this :
window[view].prototype.template = _.template(data);
new window[view]();