I have created a simple todo in react and I want to remove the selected task in todo. But when I run this code and try to delete any task, it gives an error:
firebase.child failed: First argument was an invalid path: "undefined"
componentWillMount: function() {
this.firebaseRef = new Firebase('https://simpletodosapp.firebaseio.com/todos');
var that = this;
this.firebaseRef.once('value', function(snapshot){
snapshot.forEach(function(data){
var todos = data.val();
todos['key'] = data.key;
that.setState({tasks: todos})
})
});
},
handleTodo: function(text) {
var newTask = this.state.tasks.concat(text)
this.firebaseRef.push(newTask)
this.setState({tasks: newTask})
},
handleDelete: function(task_id, key) {
this.firebaseRef.child(key).remove();
var remove = this.state.tasks.splice(task_id, 1);
this.setState({itasks: remove})
},
Related
I'm trying to pass a jasmine test for my react component, I would like to test the select all checkbox unchecks when the publish event is fired from one of the checked checkboxs. As not all all of the checkboxes will then be checked, so the select all needs to uncheck. Below is my jasmine test and component, I'm new to testing react components anyhelp much appreciated:
Currently get error, undefined is not an object this.stubs.subscribe
var React = require('react/addons');
var postal = require('postal');
var contactChannel = postal.channel("contact")
var SelectAll = require('../../../components/controls/SelectAll');
var channelStub = require('../../stub/channelStub');
// When subscribe event check checkbox
describe("Select All Checkbox Specification", function() {
describe("Checking deselect response", function () {
it("On receive subscribe event uncheck the select all box", function () {
// when the select all is created it will create the channel
// publish an event to the channel (de-select event)
instance = TestUtils.renderIntoDocument(<SelectAll />);
// publish event to check all checkboxes
contactChannel.publish({
channel: 'contact',
topic: 'selectAll',
data: {
selectAll: true
}});
var checkbox = TestUtils.findRenderedDOMComponentWithTag(instance, "input");
// publish event to uncheck select all checkbox
contactChannel.publish({
channel: "basket",
topic: "deselectedContact",
data: {}
});
// Checking the module - to see if the checkbox inside is unchecked
var checkbox = TestUtils.findRenderedDOMComponentWithTag(instance, "input");
var data = this.stubbed.subscribe();
// check box checked should be false
expect(data.topic === 'deselectedContact');
expect(input.checked === false);
});
React component:
var postal = require('postal');var postal = require('postal');
var contactChannel = postal.channel("contact");
var React = require('react');
var SelectAll = React.createClass({
getInitialState: function() {
return {
checked:false
};
},
setUnChecked: function(){
this.setState({checked: false});
},
handler: function(e) {
var updatedContacts = [],
contacts = this.props.data.contacts,
topic = 'selectAll',
checked = false,
channel = 'contact';
contactChannel.publish({
channel: channel,
topic: topic,
data: {
selectAll: event.target.checked
}});
this.setState({checked: event.target.checked});
},
render: function() {
return (
<div className="contact-selector">
<input type="checkbox" checked={this.state.checked}
onChange={this.handler} ref="checkAll" />
</div>
);
},
componentDidMount: function() {
var self = this;
contactChannel.subscribe("deselectedContact", function(data) {
self.setUnChecked();
});
}
});
module.exports = SelectAll;
ChannelStub:
var lastPublished = {},
lastTopicSubscribed = '',
lastCallbackSubscribed;
var ChannelStub = {
publish: function(data) {
lastPublished = data;
},
getLastPublished: function() {
return lastPublished;
},
subscribe: function(topic, callback) {
lastCallbackSubscribed = callback;
lastTopicSubscribed = topic;
}
};
module.exports = ChannelStub;
I am working on a soundCloud json for the favorites songs from an user.
You can see it here
I can access to my favorites tracks but i can not access to the user id and username.
Here the code i am using which returns my favorite properties and i have commented the code which is not working to return the user properties.
I get this error in the console "Uncaught TypeError: item.user.forEach is not a function"
What am i doing wrong? is it the right way to access to my user properties?
model: function(params) {
var artist, favoriteListProxy, self;
self = this;
artist = params.artist;
this.controllerFor('application').set('artistName', artist);
favoriteListProxy = Ember.ArrayProxy.create({
content: []
});
return new Ember.RSVP.Promise(function(resolve, reject) {
return SC.get("/users/" + 'mannaio' + "/favorites", {limit: 40}, function(favorites) {
if (favorites.length) {
favorites.forEach(function(item, index, arr){
var favorite;
favorite = self.createFavoritelist(item, favoriteListProxy);
// return item.user.forEach(function(user, index, arr){
// return user = self.createUser(user, favorite);
// });
});
favorites = favoriteListProxy.get('content')
return resolve(favorites);
}
});
});
},
createFavoritelist: function(favorite, arr) {
var record;
record = this.store.createRecord('favorite', {});
record.setProperties({
id: favorite.id,
title: favorite.title,
artwork_url: favorite.artwork_url,
genre: favorite.genre
});
arr.pushObject(record);
return record;
},
// createUser: function(user, favorite) {
// var record;
// record = this.store.createRecord('user', {});
// record.setProperties(user).set('favorite', favorite);
// return record;
// },
It appears to me that item.user is an Object and not an Array. Therefore it doesn't have a forEach method.
So try:
return self.createUser(item.user, favorite);
I am trying to use postal.js subscribe/publish data in my reactJs site, I am currently doing this. Can anyone tell me how to push the selected id, I think the loadContacts method is resetting the value to false:
This is my top level page:
// load initial contacts into page
loadContacts: function() {
var page = this;
ContactDirectoryService.getContacts(this.state.pageNumber, function(response) {
var contacts = response.contacts.map(function(contact){
contact.isSelected = false;
return contact;
});
page.setState({ contacts: contacts });
});
},
// postal subscribe to receive publish
componentDidMount: function() {
this.loadContacts();
var page = this;
contactChannel.subscribe("selectedContact", function(data, envelope) {
page.handleSelectedContact(data.id, page);
});
},
handleSelectedContact: function(id, page) {
var page = this;
// service to add contact using api call
BasketService.addPerson(id, function () {
console.log(id);
var arrayPush = [];
var arrayPush = page.state.selectedContacts.slice();
// push selected id to selectedContacts array
arrayPush.push(id);
page.setState({selectedContacts: arrayPush})
//add is selected to contacts
page.setState({ contacts: contacts });
// push selected id which isn't working
for(var i=0;i<page.state.contacts.length;i++)
{
var idAsNumber = parseInt(id);
if (page.state.contacts[i].id === idAsNumber) {
page.state.contacts[i].isSelected = true;
break;
}
}
basketChannel.publish({
channel: "basket",
topic: "addContactToBasket",
data: {
id: id,
newTotal: arrayPush.length
}
});
});
},
addContactToBasket: function(selectedId) {
console.log('Add ID');
console.log('Add ID');
BasketService.addPerson(selectedId, function () {
var arrayPush = [];
var arrayPush = this.state.selectedContacts.slice();
arrayPush.push(selectedId);
this.setState({selectedContacts: arrayPush})
person.isSelected = true;
basketChannel.publish({
channel: "basket",
topic: "addContactToBasket",
data: {
id: selectedId,
newTotal: arrayPush.length
}
});
});
},
Checkbox component page, to select id and publish to selectedContact channel
handler: function(e) {
e.target.value;
e.preventDefault();
channel.publish({
channel: "contact",
topic: "selectedContact",
data: {
id: e.target.attributes['data-ref'].value
}
});
},
render: function() {
return (
<div className="contact-selector">
<input type="checkbox"
checked={this.props.data.isSelected}
onChange={this.handler} />
</div>
);
},
You're passing a cached context as page, however in the first line of handleSelectedContact() you're also reinitialising the argument page into a fresh local copy of this.
my backbone collection collection doesn't populate when i just pass it in as props to a react component. I have tried first fetching the collection using componentDidmount and componentWillMount, but that still didn't populate the collection. If I test the code by setting a window variable pointing to DecksIndex and in the console tools call getInstance() and then fetch
,the data loads fine. my code is as follows:
//router.js
var DeckComponent = require("./views/deck.jsx")
var DecksIndex = React.createFactory(require("./views/decks.jsx"))
var decksCollection = require("./component/collections/decks.js");
module.exports = Backbone.Router.extend({
initialize: function(){
this.rootEl = document.getElementById('container');
},
routes: {
"":"index",
"decks/:id":"deckShow"
},
index: function(){
var decks = new DecksIndex({decks: decksCollection.getInstance()});
this._swapView(decks)
console.log("hooray!")
},
deckShow: function(id){
//var deck = Flashcards.Collections.decks.getOrFetch(id);
var showDeck = new DeckComponent();
this._swapView(showDeck);
},
_swapView: function(view){
if (this.currentView) {
React.unmountComponentAtNode(this.rootEl);
}
this.currentView = view
React.render(view, document.getElementById('container'));
}
});
//decks.js
var deck = require('../models/deck.js')
var decks = Backbone.Collection.extend({
url: "/api/decks",
model: deck,
getOrFetch: function(id){
var model = this.get(id);
var that = this;
if (model) {
model.fetch();
}else{
model = new deck({id: id})
model.fetch({
success: function(){
that.add(model)
}
})
}
return model;
},
parse: function (data) {
debugger;
return data.objects
},
});
decks.getInstance = _.memoize(function () {
return new decks();
});
module.exports = decks;
//decks.jsx
var DecksList = React.createClass({
render: function() {
return (
<div className="deck-list">
{
this.props.decks.map(function (deck) {
var title = deck.name
debugger;
return (
<div key={deck.id} className="note-summary">
{title}
</div>
);
})
}
</div>
);
}
});
module.exports = DecksList;
this is an example of a situation where a container component that manages state makes sense. If DecksList had a container that retrieved the collection when it mounted and only rendered DecksList once the data was available it would probably solve the problem. Here's a good article on the pattern: https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
The code below will create a Email Activity in CRM but I can't figure out how to add multiple recipients. If I try to add a second recipient it just replaces the first recipient.
function CreateEmail() {
alert("CreateEmail Begin");
var email = new Object();
email.Subject = "Sample Email Using REST";
SDK.JScriptRESTDataOperations.Create(email, "Email", EmailCallBack, function (error) { alert(error.message); });
}
// Email Call Back function
function EmailCallBack(result)
{
var activityParty=new Object();
// Set the "party" of the ActivityParty // EntityReference of an entity this activityparty relatated to.
activityParty.PartyId = {
Id: "8384E684-7686-E011-8AF0-00155D32042E",//replace this with the contactid from your system.
LogicalName: "contact"
};
// Set the "activity" of the ActivityParty
// EntityReference.
activityParty.ActivityId = {
Id: result.ActivityId,
LogicalName: "email"
};
// Set the participation type (what role the party has on the activity).
activityParty.ParticipationTypeMask = { Value: 2 }; // 2 mean ToRecipients
SDK.JScriptRESTDataOperations.Create(activityParty, "ActivityParty",ActivityPartyCallBack , function (error) { alert(error.message); });
}
function ActivityPartyCallBack(reuslt)
{
alert("Process Completed");
}
Here’s a snippet that creates a email with multiple Recipients. The key was to set the email_activity_parties attribute so that we can pass an object.
Essentially email_activity_parties lets us submit a Array of Object instead a top level Object.
function CreateEmail() {
debugger;
var email = new Object();
email.Subject = "my email";
email.Description = "my email description";
var activityParties = new Array();
var partyObj0 = new Object();
partyObj0.PartyId = { Id: "a9568879-e61c-e411-80bb-000c29c1100f", LogicalName: "systemuser" };
partyObj0.ParticipationTypeMask = { Value: 1 };
activityParties[0] = partyObj0;
var partyObj1 = new Object();
partyObj1.PartyId = { Id: "b23f7a24-2223-e411-80c8-000c29c1100f", LogicalName: "contact" };
partyObj1.ParticipationTypeMask = { Value: 2 };
activityParties[1] = partyObj1;
var partyObj2 = new Object();
partyObj2.PartyId = { Id: "ffd09f25-1748-e411-80cb-000c29c1100f", LogicalName: "contact" };
partyObj2.ParticipationTypeMask = { Value: 2 };
activityParties[2] = partyObj2;
//set email.email_activity_parties to activityParties
email.email_activity_parties = activityParties;
SDK.REST.createRecord(email, "Email", EmailCallBack, function (error) { alert(error.message); });
}
// Email Call Back function
function EmailCallBack(result) {
debugger;
}
Dont have a REST sample I'm afraid, but in C# SOAP you have to pass a collection of entities, perhaps its the same in REST?
Entity e = new Entity("phonecall");
e["to"] = new Entity[]
{
ToActivityParty(new EntityReference("contact", contact1)),
ToActivityParty(new EntityReference("contact", contact2)),
};
static Entity ToActivityParty(EntityReference entityReference)
{
Entity party = new Entity("activityparty");
party["partyid"] = entityReference;
return party;
}