Norfeldt Norfeldt - 1 day ago 4
React JSX Question

ReactJS: re-base helper filer for collection method calls

I have struggled a lot trying to figure out how to combine

ReactJS
and
firebase
(3).

Luckily I found the awesome re-base repo, which is awesome and exactly what I want.


fb-config.js


var Rebase = require('re-base');
var base = Rebase.createClass({
apiKey: "apiKey",
authDomain: "projectId.firebaseapp.com",
databaseURL: "https://databaseName.firebaseio.com",
storageBucket: "bucket.appspot.com",
messagingSenderId: "xxxxxxxxxxxxxx"
});
export default base;



app.js


import React, { Component } from 'react';
import base from 'fb-config';
import ExampleComponent from './components/ExampleComponent';

class App extends Component {
constructor() {
super();
// getInitialState
this.state = {
DB: {}
};
}

componentDidMount() {
this.ref = base.syncState('demo',
{ context: this,
state: 'DB' }
);
}

componentWillUnmount() {
base.removeBinding(this.ref);
}

render() {
return (
<ExampleComponent />
)
}

}

export default App



components/ExampleComponent.js


import React, { Component } from 'react';
import base from '../fb-config';

class ExampleComponent extends Component {
constructor(props, context){
super(props, context);

this.pushing = this.pushing.bind(this);
}

pushing() {
const now = new Date().getTime();
let data = {};
data[now.toString(16)] = 'Hello World';

base.fetch('demo', {
context: this,
asArray: false
}).then( snapshot => {
data = {... snapshot, ...data};
base.post('demo', {data})
.then( () = { console.log("pushed") });

});
}

render() {
return (
<button onClick={this.pushing}>PUSH</button>
)
}

};

export default ExampleComponent;


This setup works. But I would like to move the pushing method to another file (like
fb-commands.js
). How would I do that?

Answer

You can move pushing as-is, all you need is to pass context to the function, since it wont have access to the component instance via this.

// fb-commands.js
export const pushing = (context) => {
    const now = new Date().getTime();
    let data = {};
    data[now.toString(16)] = 'Hello World';

    base.fetch('demo', {
         context: context, 
         asArray: false
    }).then( snapshot => {
        data = {... snapshot, ...data};
        base.post('demo', {data})
       .then(() => console.log("pushed"));
    });
};

// components/ExampleComponent.js
import React, { Component } from 'react';
import base from '../fb-config';
import {pushing} from 'path/to/fb-commands';

class ExampleComponent extends Component {
    render() {
        return (
            <button onClick={() => pushing(this)}>PUSH</button>
        );
    }
}

export default ExampleComponent;
Comments