Giter Club home page Giter Club logo

parsereact's Introduction

WARNING ⚠️ - this project is not maintained, if you wish to maintain this project make yourself known ⚠️

Parse + React

Seamlessly bringing Parse data into your React applications.

NOTE: Parse + React only supports the Parse JS SDK up to version 1.6.14. Behavior with 1.7.* is unpredictable, and 1.8.* breaks functionality with the new LiveQueries feature. As developers, we want to encourage patterns that integrate easily into both the server and the client, and are working on a new low-level SDK that works well with Redux and React Native. When that codebase is ready for production apps, we will publish a new recommended starter kit for apps built on Parse & React.

Build Status npm version

Overview

Parse + React is an interface layer on top of the Parse JS SDK that provides simple access to the Parse API from React. It lets React components subscribe to Parse queries, and allows data mutations to be dispatched in a Flux-style manner. In the background, these subscriptions are managed in a way that lets these components automatically update as objects are created and modified, allowing user interfaces to be snappy and responsive.

Example

To add Parse data to a component, it simply needs to subscribe to a standard Parse Query. This is done through an implementation of the newly-proposed observe() API for React. The ParseReact Mixin allows a version of this new lifecycle method to be used today with Parse Queries.

If you're using React with ES6 classes, we also provide a subclass of React.Component that allows you to use the observe() and Query-specific APIs.

var CommentBlock = React.createClass({
  mixins: [ParseReact.Mixin], // Enable query subscriptions

  observe: function() {
    // Subscribe to all Comment objects, ordered by creation date
    // The results will be available at this.data.comments
    return {
      comments: (new Parse.Query('Comment')).ascending('createdAt')
    };
  },

  render: function() {
    // Render the text of each comment as a list item
    return (
      <ul>
        {this.data.comments.map(function(c) {
          return <li>{c.text}</li>;
        })}
      </ul>
    );
  }
});

Whenever this component mounts, it will issue the query and the results will be attached to this.data.comments. Each time the query is re-issued, or objects are modified locally that match the query, it will update itself to reflect these changes.

Mutations are dispatched in the manner of Flux Actions, allowing updates to be synchronized between many different components without requiring views to talk to each other. All of the standard Parse data mutations are supported, and you can read more about them in the Data Mutation guide.

// Create a new Comment object with some initial data
ParseReact.Mutation.Create('Comment', {
  text: 'Parse <3 React'
}).dispatch();

Getting Started

Parse + React is available from our CDN (minified), and npm.

If you're not familiar with React, we recommend you first walk through their tutorials before adding Parse data to your React applications.

Parse + React adds new functionality when React and the Parse JS SDK are used together, and it requires that those libraries be in place before it is initialized. The easiest way to do this is to load them on your page before loading the Parse + React library:

<html>
  <head>
    <script src="http://fb.me/react-0.13.3.min.js"></script>
    <script src="https://www.parsecdn.com/js/parse-latest.js"></script>
    <!-- Now include parse-react.js -->
    <script src="https://www.parsecdn.com/js/parse-react.js"></script>

    ...

If you're using a tool like Webpack or Browserify to enable Common JS require statements, you need to make sure you also include the 'parse' npm package in your dependencies.

var React = require('react');
var Parse = require('parse');
var ParseReact = require('parse-react');

// ...

As of version 1.6, the Parse JS SDK has a different build for React Native. If you're using Parse+React on React Native, you'll need to require the 'parse-react/react-native' package instead.

// For React Native apps
var React = require('react-native');
var Parse = require('parse/react-native');
var ParseReact = require('parse-react/react-native');

Now that you've included all of the necessary libraries, you're ready to start subscribing to Parse data and mutating it.

Contributing

See the CONTRIBUTING file for information on how to help out.

parsereact's People

Contributors

andrewimm avatar banderson avatar boopathi avatar brenmcnamara avatar dmitrysobolev avatar fozzle avatar html5cat avatar jstrutz avatar lacker avatar miwillhite avatar monirabuhilal avatar namuol avatar niveditc avatar philikon avatar soska avatar stanleyw avatar tomwfox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

parsereact's Issues

variable

var CommentBlock = React.createClass({
  mixins: [ParseReact.Mixin], // Enable query subscriptions

  observe: function() {
    // Subscribe to all Comment objects, ordered by creation date
    // The results will be available at this.data.comments
    return {
      comments: (new Parse.Query('Comment')).ascending('createdAt')
    };
  },

  render: function() {
    // Render the text of each comment as a list item
    return (
      <ul>
        {this.data.comments.map(function(c) {
          return <li>{c.text}</li>;
        })}
      </ul>
    );
  }
});

how to make a variable equals to {c.text}?

Changes to .include() in version 0.2.1

Hi!

We have an object from class "List". This object has a pointer to a user. You can change the user but we keep the initial user for logging purpose. So we end up with a Parse Object with two fields: "user" and "initial". If we query this object and .include('user'), both these fields returns with the nested objects. BUT if "user" and "initial" points to the same object, "initial" returns the nested object and "user" returns the pointer object. Same thing happens if we include "initial" instead of "user".

This did not happen in 0.2.0. This is our observe method:

observe: function() {
    return {
        list: (new Parse.Query('List')).include('user')
    };
}

In the release notes for version 0.2.1 the seconds bullet states:

When subscribing to queries that use the include() method to fetch nested objects, those nested layers will now be indexed in the ObjectStore

What exactly does this mean, and is this related to the issue we're having?

observe() Dependent on State

I have a React component with a number of tabs, each dependent on different Parse queries. I have made observe() dependent on the currently selected tab, which is stored in the component's state. When observe is called, it is done with the state before the setState() call that sets off the process. However, render is called with the state after setState(), which misaligns the the component's data with the data needed by the tab.

I believe this is because React does not update state until just before rendering (facebook/react#629).

Will this be fixed with #1?

New Parse.Files need to be saved before setting them as values

If you create a Parse.File, it needs to be saved before it can be set to an object field. The code looks something like this:

var myImage = new Parse.File(fileName, fileData);
myImage.save().then(function() {
  return ParseReact.Mutation.Set(myObject, { image: myImage }).dispatch();
});

This should be handled automatically by the Set mutation.

Webpack friendly?

I'm trying to bring parse-react into my application by requiring it via webpack, but am being thrown a few errors/warnings:

ERROR in ./~/parse/~/xmlhttprequest/lib/XMLHttpRequest.js
Module not found: Error: Cannot resolve module 'child_process' in /Users/benjennings/path/to/project/node_modules/parse/node_modules/xmlhttprequest/lib
 @ ./~/parse/~/xmlhttprequest/lib/XMLHttpRequest.js 15:12-36

ERROR in ./~/parse/~/xmlhttprequest/lib/XMLHttpRequest.js
Module not found: Error: Cannot resolve module 'fs' in /Users/benjennings/path/to/project/node_modules/parse/node_modules/xmlhttprequest/lib
 @ ./~/parse/~/xmlhttprequest/lib/XMLHttpRequest.js 16:9-2

This is probably a bad idea—but I've I managed to solve the above by adding the following to my webpack config:

  node: {
    fs: "empty",
    child_process: "empty"
  },

However I am still receiving these warnings on each successful build:

WARNING in ./~/parse-react/dist/parse-react.js
Critical dependencies:
5:483-490 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results.
 @ ./~/parse-react/dist/parse-react.js 5:483-490

WARNING in ./~/parse/build/parse-latest.js
Critical dependencies:
1263:13-16 require function is used in a way, in which dependencies cannot be statically extracted
 @ ./~/parse/build/parse-latest.js 1263:13-16

WARNING in ./~/parse/build/parse-latest.js
Module not found: Error: Cannot resolve module 'AsyncStorage' in /Users/benjennings/Documents/Coinbase/Web/central.coinbase.com/mark2/node_modules/parse/build
 @ ./~/parse/build/parse-latest.js 1956:21-40

Is there anything I should be including in my webpack config to avoid these warnings? Apologies in advance if this is more of a Webpack question than ParseReact.

Modifying collections and postponing updates

I used Parse SDK before and I could update a property on each model in the collection and when I was sure that I was ready to push the change to the server I would call save() method to sync the collection.

For instance, in a list component I used drag and drop to allow to reorder the items. I had created a handler for dragOver event that would change order attribute in my models an
a list of items. I also had provided a handler for dragOver event that would change order attribute in my models and use setState(...) to re-render the list, and a drop event handler that would save the collection.

Now that my list of items lives in this.data rather than this.state, how can I make changes to a particular attribute (e.g. order attribute) of each model in the array and cause re-render, while only sync the list when manipulating with the attributes is finished? Mutations docs or provided in the samples don't seem to cover such a scenario.

AnyBudget app is not working

parse-react.js +227 (and a couple of other places) -> uses Parse.Storage.async which I couldn't find in the documentation. Is this like an old parse implementation?

Javascript complains that this doesn't exist.

equalTo filters for join tables with pointers, on an observed query, return no results

equalTo works as expected when testing outside of React Native in a nodejs script.

However, when observing the same query in RN, no results are returned.

  observe(props, state) {
    query = new Parse.Query('PracticeSessionResource');
    query.equalTo("practice_session", props.practice_session);
    query.include("practice_resource");
    query.include("practice_session");

    return ({
      session_resources: query
    });
  },

Server side rendering.

Is it possible to render ParseReact components server side? If so, this could be a nice Relay-like framework when coupled with a router.

How to know the status of observe query result?

I've noticed that the value of this.data.comments in render(), it comes first undefined then changed to [], and finally get the all results [...], is there any way to separate between no results and query not finished these two conditions?

Or should it always return undefined before query finished?

ParseReact.Mutation.Set does not accept value with array which has null

I can do this:

item.set("array", [null, null, null]);
item.save();

but when I did:

ParseReact.Mutation.Set(item, {array: [null, null, null]}).dispatch();

I received the error Uncaught TypeError: Cannot read property 'objectId' of null

BTW,

ParseReact.Mutation.Set(item, {array: [undefined, undefined, undefined]}).dispatch();

it will work, and the saved value will be [null, null, null]

Is there a way to keep user sessions?

Looking at the AnyBudget demo, it looks like there is no way to keep the user session as of now. Is that true? If so, did anyone find a work around this?

Relational Queries in observe()

I am trying to observe the result of a relational Parse query but it looks like the observe() function returns before the Parse query has a chance to return the results needed to populate the observe function.

Here is an example of my observe function:

observe: function() {
  var self = this;

  return {
        parse_data: (self._load_parse_data())
  };
},

_load_parse_data: function(){
  // long relational parse query here
}

Is there a better way to do this?

Setting ParseReact.currentUser as pointer of a object

It seems that when creating a Mutation, passing the ParseReact.currentUser as a pointer doesn't work:

var obj = ParseReact.Mutation.Create('MyObject', {
    createdBy: ParseReact.currentUser // this is a Pointer field
}).dispatch()

in this way the object is created and persisted but the createdBy field is left empty.
Instead, by using 'classical' Parse JS sdk, it works as usual:

// object initialization here ...
// ...
object.set("createdBy", Parse.User.current())
object.save()

Is this the expected behaviour?

Error On Set Mutation

I receive an error (listed below) when trying to execute the following code:

ParseReact.Mutation.Set({className: className, objectId: objectId},{
            clockOut: new Date,
            locationClockOut: new Parse.GeoPoint(this.state.lastPosition['coords']),
          }).dispatch().then(function(results) {
              this.refreshQueries()
              this.props.onClockIn()
              this.setState({
                clockedIn: false
              })

          }.bind(this));

The className and objectId refer to a valid object in my Parse Class. I am using this in React Native. I can execute this code with no issues.

var empTime = Parse.Object.extend('EmployeeTimes')
          var query = new Parse.Query(empTime)
          query.get({className: className, objectId: objectId}, {
            success: function(rec){

              rec.set('clockOut', new Date)
              rec.set('locationClockOut',new Parse.GeoPoint(_this.state.lastPosition['coords']))
              rec.save()
              _this.refreshQueries()
              _this.props.onClockIn()
              _this.setState({
                clockedIn: false
              })

            },
            error: function(object, error){
              console.log('PArse error: ' + error);
            }

          });

This is the error:
"Error: null is not an object (evaluating 'subscriber.originalQuery')
stack:
pushUpdates index.ios.bundle:53523
issueMutation index.ios.bundle:53453
dispatch index.ios.bundle:53074
clockOutClick index.ios.bundle:58812
touchableHandlePress index.ios.bundle:34866
_performSideEffectsForTransition index.ios.bundle:33045
_receiveSignal index.ios.bundle:32969
touchableHandleResponderRelease index.ios.bundle:32772
executeDispatch index.ios.bundle:12827
forEachEventDispatch index.ios.bundle:12815
executeDispatchesInOrder index.ios.bundle:12836
executeDispatchesAndRelease index.ios.bundle:12215
forEachAccumulated index.ios.bundle:13092
processEventQueue index.ios.bundle:12422
runEventQueueInBatch index.ios.bundle:20074
handleTopLevel index.ios.bundle:20100
_receiveRootNodeIDEvent index.ios.bundle:19962
receiveTouches index.ios.bundle:20046
jsCall index.ios.bundle:7396
_callFunction index.ios.bundle:7659
index.ios.bundle:7686
index.ios.bundle:7680
perform index.ios.bundle:6194
batchedUpdates index.ios.bundle:14038
batchedUpdates index.ios.bundle:4726
index.ios.bundle:7679
applyWithErrorReporter index.ios.bundle:7431
guardReturn index.ios.bundle:7453
processBatch index.ios.bundle:7678
URL: http://localhost:8081/index.ios.bundle
line: 53523
message: null is not an object (evaluating 'subscriber.originalQuery')"

ParseReact w/o React dependencies?

Are there any plans to release a version of this library (with some of its more flux/relay-centric approaches) without a direct dependency on react?

If not, how tightly coupled are these dependencies and (realistically) can the they be separated?

For our products, we had to build a custom mobile framework, inspired by React, and have been attempting to build an immutable DataStore (based on flux and relay patterns) backed by Parse via the existing Parse JS API and custom graphql-like endpoints on CloudCode.

Would love to take advantage of the work done here (observe subs, optimistic updates, mutations, query batching, etc) if at all possible.

Thanks in advance.

Looking for Best Practice

I am structuring a common pattern of master detail where I query for the list items and then in a separate modal I allow you to add new items to the list.

When I dispatch the creation of the object in one react component,

var promise = ParseReact.Mutation.Create('TutorSession', {
    note: 'Parse <3 React',
    place: self.state.selectedPlace.id,
    tutor: self.state.selectedUser.id,
    suggestedDate: self.state.selectedDate,
    user: Parse.User.current()
}).dispatch();

// handle promise results
promise.then(function(obj) {
    // the object was saved successfully.
    console.log(obj);
    self.props.navigator.pop();
}, function(error) {
    // the save failed.
    alert("ERROR\n" + JSON.stringify(error));
});

how do I get the the List component to update? Do I need to re-run the query in the List component? This is what I am currently doing.

    observe: function () {
        return {
            tutorSessions: (new Parse.Query("TutorSession").include(["place,tutor,user"]))
        };
    },

I noticed that the query was not re-run when i reloaded the component

Bower Support

Are there any plans to add Bower support for ParseReact? Since ParseReact is mostly used in the front end, this would be really useful for a lot of developers.

ES6 Class support?

Hi, I'm working on a project that is based on React and Parse, and gladly to find this project. But, when I migrated to es6 class using babel, the [ParseReact.Mixin] seemed not working. I wonder if there is any workaround ? Thanks in advance

Issues updating query after mutation

I have the following query that I would like to automatically update after I do a create mutation:

var Group = Parse.Object.extend("Group");

observe(props, state) {
  var groupObject = new Group();
  groupObject.id = props.selectedGroupId;

  var agentQuery = new Parse.Query(Agent);
  agentQuery.equalTo("group", groupObject);

  return {agents: agentQuery};
},

When I do the following mutation, as seen in the parse javascript sdk docs, it properly creates the row in the back-end, but it doesn't trigger a react UI update:

var groupObject = new Group();
groupObject.id = groupId;

ParseReact.Mutation.Create("Agent", {
  name: name,
  group: groupObject
}).dispatch({waitForServer: true});

Looking at QueryTools.js, I tried changing the mutation to the following, and the query immediately updated in the UI:

var groupObject = new Group();
groupObject.id = groupId;
groupObject.objectId = groupId;
groupObject.className = 'Group';

ParseReact.Mutation.Create("Agent", {
  name: namee,
  group: groupObject
}).dispatch({waitForServer: true});

But this doesn't look like standard practice. What is the recommended way to dispatch a create mutation like the example I have?

Error during query in ObjectStore.deepFetch if any field is null

If I perform a query and any field of any retrieved object is null, ParseReact has this error in ObjectStore.deepFetch on the 3rd line of this excerpt

Uncaught TypeError: Cannot read property '__type' of null

for (var attr in source) {
  var sourceVal = source[attr];
  if (typeof sourceVal === 'object' && sourceVal.__type === 'Pointer') {
    var childId = new Id(sourceVal.className, sourceVal.objectId);
    if (seen.indexOf(childId.toString()) < 0 && store[childId]) {

https://github.com/ParsePlatform/ParseReact/blob/master/src/ObjectStore.js#L370

I can work around this for now by making sure my parse database never has any null fields. Would it make sense to fix it by adding an extra guard condition like sourceVal !== null?

Support Get Query

In cases where I need a single object back, I would like to setup an observe on a get query. For example,

var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
    success: function(gameScore) {
        // The object was retrieved successfully.
    },
    error: function(object, error) {
        // The object was not retrieved successfully.
        // error is a Parse.Error with an error code and message.
    }
});

https://parse.com/docs/js/guide#objects-retrieving-objects

I see there's a semi-similar ticket #39 for supporting count queries.

Extending LocalSubscription? (updated)

TLDR;

Any reason I shouldn't extend LocalSubscription to:

  1. Include other client-only data
  2. Have it listen for Dispatch events (ala Flux)

Thanks in advance.

......

Am trying to reconcile your library with my understanding of Flux's pattern of a single Dispatcher delegating Actions to multiple Datastores that components subscribe to.

Simplifying this pattern down to a single interface/ObjectStore is a breath of fresh air but I have a few questions. One of the benefits of Flux is being able to fire-and-forget actions that help marshal changes globally outside a component tree (often with data only persisted on the client and not sent to the server).

How might this be accommodated with ParseReact?

Seems like the two primary options are to implement Flux Data Stores alongside ParseReact or extend LocalSubscriptions.

Local Subscriptions allow applications to subscribe to local objects, such
as the current user. React components can watch these for changes and
re-render when they are updated.

What are your thoughts on extending LocalSubscriptions to register a callback with a dispatcher to handle different actionTypes being dispatched through the system? Callback interprets the action payload to handle it appropriately (encapsulating any needed logic). From there, using ParseReact's triggerUpdate to notify subscribed components of the changes.

Seems like this approach would greatly eliminate the overhead of passing props through an entire component tree (since nested components can subscribe directly to LocalSubscription as needed) and for dealing with data between components that don't have a parent-child relationship.

Love your thoughts... thanks in advance.

Any plans to make this work with cloud code?

Can this work in the cloud code environment? I assume because it relies on the Javascript SDK that its more browser based than anything.

The cloud code environment would benefit from React integration (for the views at least).

React-native and Facebook login

I'm up&running with react-native and ParseReact, including Parse.User login/signup.

I'm stucked, however, on Facebook user login. I'm following this guide:
https://www.parse.com/docs/js/guide#users-facebook-users
but the FB JS sdk can't be added (Can't find variable: document).

Any idea/direction? I'm also happy to go for solutions that use Facebook iOS sdk, similarly as [1], but I don't know what's the level of integration of Parse with that. Thanks a lot!

[1] https://github.com/magus/react-native-facebook-login

ObjectStore.js fail to handle null in Number datatype

var first = new Parse.Object('Item');
first.set('quantity', 0); // first set Datatype to Number
first.save();

var second = new Parse.Object('Item');
second.set('quantity', NaN); // `NaN` would be store as `null` in Database
second.save();

observe: function(props) { // this `null` would trigger error in ObjectStore.js
    return {
        items: (new Parse.Query('Item')).greaterThan('quantity', 0)
    };
}

Limit setting not being preserved after subsequent updates

Hello! Just playing around with this for a demo I'm putting together and noticed limit is not preserved when you update data over time using ParseReact.Mutation.Create. I can put together a jsFiddle or something if that helps, but perhaps code speaks louder? See #18 for how I fixed it locally.

Requiring unknown module "parse".

var Parse = require('parse');
console.log(Parse);

Requiring unknown module "parse". If you are sure the module is there, try restarting the packager."

Environment

  • Parse 1.4.2
  • ReactNative 0.4.0
  • Webpack 1.8.10

packages.json

{
  "private": true,
  "name": "Nom",
  "version": "0.0.1",
  "scripts": {
    "start": "./node_modules/.bin/react-native-webpack-server start --port 3000 --packagerPort 3001 --webpackPort 3002"
  },
  "dependencies": {
    "babel-core": "^5.1.13",
    "babel-loader": "^5.0.0",
    "immstruct": "git+https://github.com/omniscientjs/immstruct.git",
    "parse": "^1.4.2",
    "react": "^0.13.2",
    "react-hot-loader": "^1.2.5",
    "react-native": "^0.4.0",
    "react-native-camera": "^0.2.0",
    "react-native-facebook-login": "^0.4.5",
    "react-native-webpack-server": "git+https://github.com/mjohnston/react-native-webpack-server.git",
    "uuid": "^2.0.1",
    "webpack": "^1.8.10",
    "webpack-dev-server": "^1.8.2"
  }
}

Other modules I have installed work just fine.

Caching ?

Hi,

I have a few questions about caching :

  • With an infinite scroll where only the limit parameter is changing, it would be nice to only query the missing objects.
    Currently it is not so great : when the limit changes it renders a first time without the firsts elements then it rerenders with all elements. it causes flickering.
  • It would be nice to add a mechanism to store/load the ObjectStore (allowing the developer to choose the method of his choice [Async Storage on react native, Locastorage/... on Web]) so that when returning to the app it displays the stored objects until it eventually gets updated.
    I guess Subscription would need changes too.
  • I also want to store the mutations if they don't get a response when submitted to the server (if there is no available connection for example) and to replay them until it gets a response. Even if the tab (or the app) is closed/reopened.
    I believe changes would need to be implemented in the UpdateChannel (auto retry, and getting stored pending mutations on start) ?

This issue is more of a feedback afterall....

Currently i think i'll need to make my specific Store and Actions if i want to achieve the result i want.

Thank you

Fork and Licensing

I've read the license file and it seems to be related just to Parse backend.

Am I allowed to fork ParseReact to integrate other Back-end as a Service systems with React?

Decrement Mutations

I've run into a situation where the Increment Mutation has proved very useful, it keeps the client from writing stale data to Parse and keeps the update to the UI very quick and snappy.
I was looking through the docs and Mutation.js and noticed that there is not a Decrement Mutation. I realize a Decrement Mutation proves to be a bit more tricky that an Increment Mutation because of negative numbers, but I was wondering if anything was in the works for this Mutation or if this is something that could be submitted as a future pull request?

Cannot Gain Access to single Object

When I have a query that results in a single query object. How do I get access to the properties of that object? I have to use map for everything? That seems to be the only way to gain access. Further, I have a row with a pointer and I had to manually create a pointer record to get the query to work properly. So I end up with a single query object but cannot do anything with it except map, which makes no damn sense.

   observe: function(props, state) {

        var p = {
         "__type": "Pointer",
         "className": "ports",
         "objectId": this.props.port.objectId
     };
        return {
            ports: (new Parse.Query('ports').equalTo('connected_to_1', p))
        }
    },
    render: function() {
        var port = this.data.ports[0];
        console.log(port);

        return (
            <div>
                port
            </div>
        );
    }
});

Object {id: 3.Id, className: "ports", objectId: "NJk27dgg8B", createdAt: Tue Apr 14 2015 20:17:25 GMT-0600 (MDT), updatedAt: Tue Apr 14 2015 20:18:45 GMT-0600 (MDT)}

The console shows the object above but I cannot get to any of the properties. Further, it is not a Parse object. So what is it?

module error

can someone help me on setting parse up with react native?

var Parse = require('parse').Parse;

this is the only line that i have and it gives me the error image below

screen shot 2015-04-30 at 9 14 11 am

It shows that it needs xmlhttprequest module. So I added it.
However, when I added it, it shows another module issues saying that theres a unknown module "url" required.

screen shot 2015-04-30 at 9 18 28 am

Querying for objects equalTo current user doesn't respond to mutations.

Apologies in advance if I'm misunderstanding something fundamental about ParseReact but I'm having an issue regarding creating objects associated with the current parse user.

I have a component with the following observe method:
observe: function() { return { places: (new Parse.Query('Place')) .equalTo('user', Parse.User.current()) .descending('createdAt') }; }

However when I create a new 'Place' object:

ParseReact.Mutation.Create('Place', { name: 'New Place', user: Parse.User.current() }).dispatch();

...the component doesn't re-render as expected.

Related StackOverflow issue: http://stackoverflow.com/questions/29800798/parse-react-observe-objects-created-by-parse-user-current

Issue with Set Mutations

I have been experiencing issues with Set Mutations. Every time I try and create a very basic Set Mutation, like so:

var dispatch_activity = ParseReact.Mutation.Set(parseObj.id, { update_field: String(c) } );

///
dispatch_activity.dispatch();

I would get the following error:

Uncaught TypeError: Cannot read property 'className' of undefined   parse-react.js:2497

Based upon the documentation and the todo Demo it looked like my code was correct, so I thought I would take a look at the code in parse-react.js at 2497.

On the code in parse-react.js it looks like the changes object is referencing id.className from the latest object, which I found not to hold that data. Here is the snippet I am referring to:

var potentials = SubscriptionManager.queriesForFields(changes.latest.id.className, changes.fields);
  for (i = 0; i < potentials.length; i++) {
    if (visited[potentials[i]]) {
      continue;
    }
    subscriber = SubscriptionManager.getSubscription(potentials[i]);
    if (QueryTools.matchesQuery(changes.latest, subscriber.originalQuery)) {
      subscriber.addResult(changes.latest);
      ObjectStore.addSubscriber(changes.latest.id, potentials[i]);
    }
  }
  if (changes.latest.id.className === '_User') {
    var currentUser = Parse.User.current();
    if (currentUser && changes.latest.id.objectId === currentUser.id) {
      LocalSubscriptions.currentUser.update(changes.latest);
    }
  }

If I reworked this block of code for changes to reference id.className directly then everything worked perfectly in my Set Mutation. Like so:

  var potentials = SubscriptionManager.queriesForFields(changes.id.className, changes.fields);
  for (i = 0; i < potentials.length; i++) {
    if (visited[potentials[i]]) {
      continue;
    }
    subscriber = SubscriptionManager.getSubscription(potentials[i]);
    if (QueryTools.matchesQuery(changes.latest, subscriber.originalQuery)) {
      subscriber.addResult(changes.latest);
      ObjectStore.addSubscriber(changes.id, potentials[i]);
    }
  }
  if (changes.id.className === '_User') {
    var currentUser = Parse.User.current();
    if (currentUser && changes.id.objectId === currentUser.id) {
      LocalSubscriptions.currentUser.update(changes.latest);
    }
  }

Just wondering if anyone else has seen this issue or if it is something that I am possibly doing wrong.

QueryTools.stringify fails on null values

I have a field on my Parse model that has null as a value. This should be valid, but when it hits the QueryTools.stringify method I get the following error:

Uncaught TypeError: Cannot convert undefined or null to object
    at Function.keys (native)
    at eval (eval at evaluate (unknown source), <anonymous>:1:8)
    at Object.InjectedScript._evaluateOn (<anonymous>:895:55)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluateOnCallFrame (<anonymous>:954:21)
    at stringify (http://localhost:4000/js/main.js:3687:3)
    at stringify (http://localhost:4000/js/main.js:3690:46)
    at Array.map (native)
    at stringify (http://localhost:4000/js/main.js:3682:23)
    ...

react-native compatability

Assuming this is a use case that we would want to support in the future, it seems to not be working as expected in my root react-native app component.

var React = require('react-native');
var Parse = require('parse').Parse;
var ParseReact = require('parse-react');

// Make react and parse global
window.React = React;
window.Parse = Parse;
window.ParseReact = ParseReact;

throws...
screen shot 2015-03-29 at 9 57 52 pm

Inconsistent pointer type in query results after issuing Mutation.Create

I have a query that automatically updates when I issue a Mutation.Create. However, the pointer values of my results are inconsistent between objects that were pulled from the server and objects that were just added via the Mutation.Create.

  • The objects that came from the server were flattened, so their id is in a field called objectId.
  • The objects that came from the mutation are ordinary parse object pointers (just like in the Mutation.Create), so their id is in a field called id.

This makes it challenging to use query results, since I constantly have to check what type the pointers are.

Below is an example component where this occurs:

const React = require('react');
const Parse = require('parse').Parse;
const ParseReact = require('parse-react');

const Comment = Parse.Object.extend('Comment');
const User = Parse.Object.extend('User');

const CommentBox = React.createClass({
  mixins: [ParseReact.Mixin],

  observe() {
    return {comments: new Parse.Query(Comment)};
  },

  handleNewComment(event) {
    event.preventDefault();
    ParseReact.Mutation.Create('Comment', {
      body: React.findDOMNode(this.refs.newComment).value,
      user: new User({id: this.props.curUser.objectId}),
    }).dispatch();
  },

  render() {
    console.log(this.data.comments.map(x => x.user.id));
    console.log(this.data.comments.map(x => x.user.objectId));
    return (
      <form onSubmit={this.handleNewComment}>
        <input type="text" ref="newComment" />
        <button type="submit">Send</button>
      </form>
    );
  },
});

module.exports = CommentBox;

When loading the page, the console log looks like:

[Id, Id]
["W4fOmMXg", "W4fOmMXg"]

After submitting a comment, it outputs:

[Id, Id, "W4fOmMXg"]
["W4fOmMXg", "W4fOmMXg", undefined]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.