Giter VIP home page Giter VIP logo

benwinding / react-admin-firebase Goto Github PK

View Code? Open in Web Editor NEW
460.0 19.0 170.0 67.02 MB

A firebase data provider for the react-admin framework

Home Page: https://benwinding.github.io/react-admin-firebase/

License: MIT License

TypeScript 80.24% HTML 0.82% JavaScript 18.82% CSS 0.12%
react-admin firestore firestore-dataprovider react firebase firebase-auth firebase-authui low-code-development-platform low-code

react-admin-firebase's Introduction

react-admin-firebase

NPM Version License Downloads/week Github Issues

A firebase data provider for the React-Admin framework. It maps collections from the Firebase database (Firestore) to your react-admin application. It's an npm package!


Features

  • Firestore Dataprovider (details below)
  • Firebase AuthProvider (email, password)
  • Login with: Google, Facebook, Github etc... (Example Here)
  • Forgot password button... (Example Here)
  • Firebase storage upload functionality, with upload monitoring... (Example Here)

Pull requests welcome!!

Firestore Dataprovider Features

  • Dynamic caching of resources
  • All methods implemented; (GET, POST, GET_LIST ect...)
  • Filtering, sorting etc...
  • Ability to manage sub collections through app configuration
  • Ability to use externally initialized firebaseApp instance
  • Override firestore random id by using "id" as a field in the Create part of the resource
  • Upload to the firebase storage bucket using the standard <FileInput /> field
  • Realtime updates, using ra-realtime
    • Optional watch collection array or dontwatch collection array

Get Started

yarn add react-admin-firebase firebase

or

npm install --save react-admin-firebase firebase

Demos Basic

A simple example based on the React Admin Tutorial.

Prerequisits

  • Create a posts collection in the firebase firestore database
  • Get config credentials using the dashboard

Options

import {
  FirebaseAuthProvider,
  FirebaseDataProvider,
  FirebaseRealTimeSaga
} from 'react-admin-firebase';

const config = {
  apiKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  authDomain: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  databaseURL: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  projectId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  storageBucket: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  messagingSenderId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
};

// All options are optional
const options = {
  // Use a different root document to set your resource collections, by default it uses the root collections of firestore
  rootRef: 'root-collection/some-doc' | () => 'root-collection/some-doc',
  // Your own, previously initialized firebase app instance
  app: firebaseAppInstance,
  // Enable logging of react-admin-firebase
  logging: true,
  // Resources to watch for realtime updates, will implicitly watch all resources by default, if not set.
  watch: ['posts'],
  // Resources you explicitly dont want realtime updates for
  dontwatch: ['comments'],
  // Authentication persistence, defaults to 'session', options are 'session' | 'local' | 'none'
  persistence: 'session',
  // Disable the metadata; 'createdate', 'lastupdate', 'createdby', 'updatedby'
  disableMeta: false,
  // Have custom metadata field names instead of: 'createdate', 'lastupdate', 'createdby', 'updatedby'
  renameMetaFields: {
    created_at: 'my_created_at', // default: 'createdate'
    created_by: 'my_created_by', // default: 'createdby'
    updated_at: 'my_updated_at', // default: 'lastupdate'
    updated_by: 'my_updated_by', // default: 'updatedby'
  },
  // Prevents document from getting the ID field added as a property
  dontAddIdFieldToDoc: false,
  // Adds 'deleted' meta field for non-destructive deleting functionality
  // NOTE: Hides 'deleted' records from list views unless overridden by filtering for {deleted: true} 
  softDelete: false,
  // Changes meta fields like 'createdby' and 'updatedby' to store user IDs instead of email addresses
  associateUsersById: false,
  // Casing for meta fields like 'createdby' and 'updatedby', defaults to 'lower', options are 'lower' | 'camel' | 'snake' | 'pascal' | 'kebab'
  metaFieldCasing: 'lower',
  // Instead of saving full download url for file, save just relative path and then get download url
  // when getting docs - main use case is handling multiple firebase projects (environments)
  // and moving/copying documents/storage files between them - with relativeFilePaths, download url
  // always point to project own storage
  relativeFilePaths: false, 
  // Add file name to storage path, when set to true the file name is included in the path
  useFileNamesInStorage: false,
  // Use firebase sdk queries for pagination, filtering and sorting
  lazyLoading: {
    enabled: false
  },
  // Logging of all reads performed by app (additional feature, for lazy-loading testing)
  firestoreCostsLogger: {
    enabled: false,
    localStoragePrefix // optional
  },
  // Function to transform documentData before they are written to Firestore
  transformToDb: (resourceName, documentData, documentId) => documentDataTransformed
}

const dataProvider = FirebaseDataProvider(config, options);
const authProvider = FirebaseAuthProvider(config, options);
const firebaseRealtime = FirebaseRealTimeSaga(dataProvider, options);

Data Provider

import * as React from 'react';
import { Admin, Resource } from 'react-admin';

import { PostList, PostShow, PostCreate, PostEdit } from "./posts";
import {
  FirebaseAuthProvider,
  FirebaseDataProvider,
  FirebaseRealTimeSaga
} from 'react-admin-firebase';

const config = {
  apiKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  authDomain: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  databaseURL: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  projectId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  storageBucket: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
  messagingSenderId: "aaaaaaaaaaaaaaaaaaaaaaaaaaa",
};

const options = {};

const dataProvider = FirebaseDataProvider(config, options);
...
      <Admin 
        dataProvider={dataProvider} 
      >
        <Resource name="posts" list={PostList} show={PostShow} create={PostCreate} edit={PostEdit}/>
      </Admin>
...

Auth Provider

Using the FirebaseAuthProvider you can allow authentication in the application.

const dataProvider = FirebaseDataProvider(config);
const authProvider = FirebaseAuthProvider(config);
...
      <Admin 
        dataProvider={dataProvider}
        authProvider={authProvider}
      >
...

Also checkout how to login with: Google, Facebook, Github etc... (Example Here)

And you might want a "Forgot password" button... (Example Here)

Note

To get the currently logged in user run const user = await authProvider.checkAuth(), this will return the firebase user object, or null if there is no currently logged in user.

Realtime Updates!

NOTE: Realtime updates were removed in react-admin v3.x (see marmelab/react-admin#3908). As such, react-admin-firebase v3.x also does not support Realtime Updates. However, much of the original code used for this functionality in react-admin v2.x remains - including the documentation below. For updates on the implementation of realtime please follow these issues:

Get realtime updates from the firebase server instantly on your tables, with minimal overheads, using rxjs observables!

...
import {
  FirebaseRealTimeSaga,
  FirebaseDataProvider
} from 'react-admin-firebase';
...
const dataProvider = FirebaseDataProvider(config);
const firebaseRealtime = FirebaseRealTimeSaga(dataProvider);
...
      <Admin 
        dataProvider={dataProvider} 
        customSagas={[firebaseRealtime]}
      >
...

Realtime Options

Trigger realtime on only some routes using the options object.

...
const dataProvider = FirebaseDataProvider(config);
const options = {
  watch: ['posts', 'comments'],
  dontwatch: ['users']
}
const firebaseRealtime = FirebaseRealTimeSaga(dataProvider, options);
...

Upload Progress

Monitor file upload data using custom React component which listen for following events (CustomEvent):

  • FILE_UPLOAD_WILL_START
  • FILE_UPLOAD_START
  • FILE_UPLOAD_PROGRESS
  • FILE_UPLOAD_PAUSED
  • FILE_UPLOAD_CANCELD
  • FILE_UPLOAD_COMPLETE
  • FILE_SAVED

All events have data passed in details key:

  • fileName: the file anme
  • data: percentage for FILE_UPLOAD_PROGRESS

Events are sent to HTML DOM element with id "eventMonitor". See demo implementation for example at src-demo/src/App.js;

Help Develop react-admin-firebase?

  1. git clone https://github.com/benwinding/react-admin-firebase
  2. yarn
  3. yarn start-demo

Now all local changes in the library source code can be tested immediately in the demo app.

Run tests

To run the tests, either watch for changes or just run all tests.

  • yarn test-watch
  • yarn test

paypal

react-admin-firebase's People

Contributors

adamfilipek92 avatar amilosmanli avatar benfoley avatar benwinding avatar cjsewell avatar dastannesaei avatar davidstackio avatar dependabot[bot] avatar dvasdekis avatar ecunniet avatar gmenti avatar gstvg avatar heyfife avatar hffmnn avatar laszlodev avatar marceltn avatar marianoamado avatar matheusmoura17 avatar milyiyo avatar nathan815 avatar qbantek avatar rwoverdijk avatar sethcwhiting avatar simonbuerger avatar tarunkishore2303 avatar wprk avatar yaneq avatar ywroh 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

react-admin-firebase's Issues

Error on performing "yarn watch"

Error in console:

yarn run v1.16.0
$ microbundle watch
node-resolve: setting options.module is deprecated, please override options.mainFields instead
node-resolve: setting options.jsnext is deprecated, please override options.mainFields instead
node-resolve: setting options.module is deprecated, please override options.mainFields instead
node-resolve: setting options.jsnext is deprecated, please override options.mainFields instead
node-resolve: setting options.module is deprecated, please override options.mainFields instead
node-resolve: setting options.jsnext is deprecated, please override options.mainFields instead
Watching source, compiling to dist:
(rpt2 plugin) Error: /home/jeremias/Proyectos/react-admin-firebase/src/providers/database/FirebaseClient.ts(18,5): semantic error TS2741 Property 'clearPersistence' is missing in type 'Firestore' but required in type 'FirebaseFirestore'.
Error: /home/jeremias/Proyectos/react-admin-firebase/src/providers/database/FirebaseClient.ts(18,5): semantic error TS2741 Property 'clearPersistence' is missing in type 'Firestore' but required in type 'FirebaseFirestore'.
    at error (/home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup/dist/rollup.js:3460:30)
    at Object.error (/home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup/dist/rollup.js:21251:17)
    at RollupContext.error (/home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:17186:30)
    at /home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:24943:23
    at arrayEach (/home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:532:11)
    at forEach (/home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:9360:14)
    at printDiagnostics (/home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:24916:5)
    at Object.transform (/home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup-plugin-typescript2/dist/rollup-plugin-typescript2.cjs.js:26582:17)
    at /home/jeremias/Proyectos/react-admin-firebase/node_modules/rollup/dist/rollup.js:20962:25

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

DateTime and Date gets updated as string instead of timestamp

On any form with Date or DateTime input fields data usually is set as timestamp. This works as long as there is new input (like on a create form or and edit form as long as you actually edit these fields). It happens that if you don't change the input of these fields it gets updated (which it shouldn't in the first place as it wasn't changed) and gets updated as string.

createdate and lastupdate

Hi,
Any chance to add createdate and lastupdate fields for insert/update in firebase? It would be very useful!

getAbsolutePath returns wrong path

HI there,
getAbsolutePath returns wrong path which lead to resource not found then collection of undefined.
https://github.com/benwinding/react-admin-firebase/blob/dee10e43048aa23b148d5efdd7b03ea2ff3a3606/src/misc/pathHelper.ts

my config is like so:

const options = {
logging: true,
debug: true,
rootRef: 'root_collection/GXLak3jr1WMSN8SGijoH',
watch: ["posts"]
}

const absolutePath = getAbsolutePath(this.options.rootRef, relativePath);

image
image

it should be '/root_collection/GXLak3jr1WMSN8SGijoH/posts/ not 'root_collection/GXLak3jr1WMSN8SGijoH' which is the wrong path,

the slice you are doing in the aboslute path helper is the cause I think

Wrong type stored in Firebase on Edit

Hi, I don't have much experience with JS or React so my question might not be exactly related to the library implementation but in my previous version of admin panel (without this library) everything worked correctly.

I have a simple form with text input. The source of this field is Number in Firebase, but on edit value from input is passed as String. On edit action the type is being changed to String.

...
<TextInput source = "position" label = "# Position"/>
...

Before edit
position: 5
After edit
position: "5"

Is this library issue and if not, what could be done to prevent this behavior? Thank you.

Error on opening create form

Hi Ben, I left a comment on the open issue but then noticed it was a dupe. After some more digging it started to look like a slightly different issue. From what I can see it appears that react-admin is expecting the ID prop and is therefore chucking an error when attempting to open the ../create route. I have screenied the console output

image

Full trace:
index.js:1452 Warning: Failed prop type: The prop id is marked as required in Edit, but its value is undefined.
in Edit (created by WithStyles(Edit))
in WithStyles(Edit) (at OrgEdit.js:9)
in OrgEdit (created by WithPermissions)
in WithPermissions (created by Connect(WithPermissions))
in Connect(WithPermissions) (created by getContext(Connect(WithPermissions)))
in getContext(Connect(WithPermissions)) (created by Route)
in Route (created by Resource)
in Switch (created by Resource)
in Resource (created by Connect(Resource))
in Connect(Resource) (at AdminApp.js:18)
in Route (created by RoutesWithLayout)
in Switch (created by RoutesWithLayout)
in RoutesWithLayout (created by Route)
in div (created by Layout)
in main (created by Layout)
in div (created by Layout)
in div (created by Layout)
in Layout (created by WithStyles(Layout))
in WithStyles(Layout) (created by Route)
in Route (created by withRouter(WithStyles(Layout)))
in withRouter(WithStyles(Layout)) (created by Connect(withRouter(WithStyles(Layout))))
in Connect(withRouter(WithStyles(Layout))) (created by LayoutWithTheme)
in MuiThemeProvider (created by LayoutWithTheme)
in LayoutWithTheme (created by Route)
in Route (created by CoreAdminRouter)
in Switch (created by CoreAdminRouter)
in div (created by CoreAdminRouter)
in CoreAdminRouter (created by Connect(CoreAdminRouter))
in Connect(CoreAdminRouter) (created by getContext(Connect(CoreAdminRouter)))
in getContext(Connect(CoreAdminRouter)) (created by Route)
in Route (created by CoreAdmin)
in Switch (created by CoreAdmin)
in Router (created by ConnectedRouter)
in ConnectedRouter (created by CoreAdmin)
in TranslationProviderView (created by Connect(TranslationProviderView))
in Connect(TranslationProviderView) (created by CoreAdmin)
in Provider (created by CoreAdmin)
in CoreAdmin (created by withContext(CoreAdmin))
in withContext(CoreAdmin) (at AdminApp.js:13)
in AdminApp (created by Route)
in Route (at App.js:65)
in AuthProvider (at App.js:57)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:56)
in App (at src/index.js:7)
function.console.(anonymous function) @ index.js:1452
printWarning @ checkPropTypes.js:20
checkPropTypes @ checkPropTypes.js:75
validatePropTypes @ react.development.js:1682
createElementWithValidation @ react.development.js:1775
render @ withStyles.js:327
finishClassComponent @ react-dom.development.js:14899
updateClassComponent @ react-dom.development.js:14863
beginWork @ react-dom.development.js:15716
performUnitOfWork @ react-dom.development.js:18750
workLoop @ react-dom.development.js:18791
renderRoot @ react-dom.development.js:18876
performWorkOnRoot @ react-dom.development.js:19812
performWork @ react-dom.development.js:19722
performSyncWork @ react-dom.development.js:19696
interactiveUpdates$1 @ react-dom.development.js:19984
interactiveUpdates @ react-dom.development.js:2267
dispatchInteractiveEvent @ react-dom.development.js:5081
index.js:1452 Warning: Failed prop type: The prop id is marked as required in EditController, but its value is undefined.
in EditController (created by Context.Consumer)
in translate(EditController) (created by Connect(translate(EditController)))
in Connect(translate(EditController)) (created by Edit)
in Edit (created by WithStyles(Edit))
in WithStyles(Edit) (at OrgEdit.js:9)
in OrgEdit (created by WithPermissions)
in WithPermissions (created by Connect(WithPermissions))
in Connect(WithPermissions) (created by getContext(Connect(WithPermissions)))
in getContext(Connect(WithPermissions)) (created by Route)
in Route (created by Resource)
in Switch (created by Resource)
in Resource (created by Connect(Resource))
in Connect(Resource) (at AdminApp.js:18)
in Route (created by RoutesWithLayout)
in Switch (created by RoutesWithLayout)
in RoutesWithLayout (created by Route)
in div (created by Layout)
in main (created by Layout)
in div (created by Layout)
in div (created by Layout)
in Layout (created by WithStyles(Layout))
in WithStyles(Layout) (created by Route)
in Route (created by withRouter(WithStyles(Layout)))
in withRouter(WithStyles(Layout)) (created by Connect(withRouter(WithStyles(Layout))))
in Connect(withRouter(WithStyles(Layout))) (created by LayoutWithTheme)
in MuiThemeProvider (created by LayoutWithTheme)
in LayoutWithTheme (created by Route)
in Route (created by CoreAdminRouter)
in Switch (created by CoreAdminRouter)
in div (created by CoreAdminRouter)
in CoreAdminRouter (created by Connect(CoreAdminRouter))
in Connect(CoreAdminRouter) (created by getContext(Connect(CoreAdminRouter)))
in getContext(Connect(CoreAdminRouter)) (created by Route)
in Route (created by CoreAdmin)
in Switch (created by CoreAdmin)
in Router (created by ConnectedRouter)
in ConnectedRouter (created by CoreAdmin)
in TranslationProviderView (created by Connect(TranslationProviderView))
in Connect(TranslationProviderView) (created by CoreAdmin)
in Provider (created by CoreAdmin)
in CoreAdmin (created by withContext(CoreAdmin))
in withContext(CoreAdmin) (at AdminApp.js:13)
in AdminApp (created by Route)
in Route (at App.js:65)
in AuthProvider (at App.js:57)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:56)
in App (at src/index.js:7)
function.console.(anonymous function) @ index.js:1452
printWarning @ checkPropTypes.js:20
checkPropTypes @ checkPropTypes.js:75
validatePropTypes @ react.development.js:1682
createElementWithValidation @ react.development.js:1775
(anonymous) @ translate.js:101
updateContextConsumer @ react-dom.development.js:15558
beginWork @ react-dom.development.js:15757
performUnitOfWork @ react-dom.development.js:18750
workLoop @ react-dom.development.js:18791
renderRoot @ react-dom.development.js:18876
performWorkOnRoot @ react-dom.development.js:19812
performWork @ react-dom.development.js:19722
performSyncWork @ react-dom.development.js:19696
interactiveUpdates$1 @ react-dom.development.js:19984
interactiveUpdates @ react-dom.development.js:2267
dispatchInteractiveEvent @ react-dom.development.js:5081
index.js:1452 Warning: Missing translation for key: "react-admin-firebase: No id found matching: undefined"

warning thrown by webpack due to incorrect firebase imports

Using CRA v2 and webpack 4 warnings are generated on startup :

It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.

For the module builds, these are available in the following manner
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):

CommonJS Modules:
const firebase = require('firebase/app');
require('firebase/<PACKAGE>');

ES Modules:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';

Typescript:
import * as firebase from 'firebase/app';
import 'firebase/<PACKAGE>';

This is because of the way Firebase is imported in firebaseAuthProvider.ts and firebaseDataProvider : it should be import * as firebase from "firebase/app"; instead of import * as firebase from "firebase";.

see issue firebase/firebase-js-sdk#848

ability to disable metadata

Currently, several metadata fields are automatically created/updated, like createdate, lastupdate, createdby and updatedby. This leaks information (for example, the email addresses of admin users) into documents that may be publicly accessible, and should be able to be disabled.

I can make a PR to add an option like nometadata if that would be acceptable.

High Reads

I have around 5000 records. Reads climbs up 5K everytime opening dashboad

Root path for collections

I have firestore set up in such a way that different "organisations" have their own root path, so I can easily restrict their access to that specific collection.

Right now, using react-admin-firebase this works:

<Resource options={{ label: 'Categories' }} name='organisation/BQ0S2IpuKE6YWmt8FwAe/categories' />

Which is okay, but looks weird. It'd be nice to be able to set a basePath for references. I'm thinking of something like this:

const dataProvider = FirebaseDataProvider(config, { rootPath: 'organisation/BQ0S2IpuKE6YWmt8FwAe');

// ...

<Resource name='categories' />

Feel free to let me know if you think it's a dumb idea 😄

Update: I think I should have called it a rootRef. Everything is a ref anyway.

Edit not working

react-admin-firebase: No id found matching: some_id_here

When directly navigating to a specific id to edit, it's not found. I think this is due to how data is loaded.

Error on create

Hi @benwinding, your job is ansome! react-admin-firebase works very fine!

When i create new doc i get this error on console:
The response to 'CREATE' must be like { data: { id: 123, ... } }, but the received data does not have an 'id' key. The dataProvider is probably wrong for 'CREATE'

I tried to redirect to list instead show, but the error ocurs and not redirect.

I struggled studing your code, but didn't have much success. I think the error occur because the method add on firebase is async and you return data without id.
I resolved the error passing a constant id, but obviously is not the right think to do.

File firebaseDataProvider.js
Method apiCreate changing line 157

return [2 /*return*/, { data: __assign({}, params.data) }];

return [2 /*return*/, { data: __assign({}, params.data, { id: "temp"}) }];

I am comming from C# and not have much experience with JS, i did any mistake using your lib or we have a issue?

Import error with CRA v2 (webpack 4)

description

Using create-react-app v2, an error is thrown on start : "Can't import the named export 'AUTH_CHECK' from non EcmaScript module"

workaround

add type: 'javascript/auto', in module section of webpack.config.js.

explanation

modules with mjs extension are now treated differently by webpack 4 :

Files ending with .mjs are parsed as javascript/esm, a stricter mode. This mode does not allow to import CJS modules like ESM ones.

source : apollographql/react-apollo#1737

Similar issue with react-appolo :

In react-apollo, react-apollo.browser.umd.js is evaluated by webpack as javascript/auto (webpack 3 default mode). It is a loose mode to preserve compatibility that support both CJS and ESM within the same file. When webpack parses require("./ApolloProvider") it will look at ./ApolloProvider.mjs first.

While this issue looks like a webpack one, it is not: react-apollo should correctly import non-ESM dependencies, in this case react.

version

react-admin-firebase v0.5.1

Support for initialValues prop in Create?

React-admin lets you pass in an initialValues object to <SimpleForm> to specify a set of default values when creating a record (ref).

Does react-admin-firebase contain support for the initialValues prop?

In my project, the object passed to initialValues is ignored. Example:

const defaultValues = {
      createdAt: new Date().getTime(),
      ....
    }

<SimpleForm initialValues={defaultValues}>
      <TextInput source="first_name" />
</SimpleForm>

We'd expect the newly created record to contain the fields in defaultValues.

Prettier rules

hey @benwinding, would you be open to add some prettier rules to the project, so we have a definition for the code formatting?
The project does missing some consistency of the code formatting in few files. Like ' or " quoation or spacings. A prettier config would set a default with we can agree on and so have a common stying definition when contributing to the package.

I can open a PR if you are open to it.
Thanks Laszlo

Full auth functionality

The current solution provided by this library adheres best to react admin's default flow. However, this does limit the use cases of Firebase Auth to only the e-mail+password possibility. It would be nice to have default components (custom routes, sagas, screens, etc.) to allow the use of the full Firebase Auth possibilities.

I've already done something similar using Auth0, and this works pretty well, so for sure it is possible. I've yet to do the same for Firebase Auth, but I find the documentation much more confusing than the one from Auth0. If I I get to it, and manage to make it work, I'll share you my implementation. If I manage to make it reusable, I might even PR it. 😁

suggestion: modify HandleAuthCheck in firebaseAuthProvider.ts

Hi,
May I suggest to modify this function adding return Promise.reject(); ?
Reasons: the authentication is working perfectly agains firebase. However, no resource is protected once you're not logged in and try to access.... So Promise.reject() makes sense once the user is logged off and tries to access to a resource....

async HandleAuthCheck(params) { try { const user = await this.getUserLogin(); log("HandleAuthCheck: user is still logged in", { user }); } catch (e) { log("HandleAuthCheck: ", { e }); return Promise.reject(); } }

Meta Programming (@Collection & #Tag Search)

Ever since I used the Toggl timer bar and Slack search I have wished for the @Account #Topic search functions to become a dev standard.

Note: I wrote about this idea in #59 (comment) if you want to read my initial mumblings.

eg searching in:

Toggl timer bar with Projects and Tags but with out the @ and # drop down feature in the general text area. (incidentilly github does this for people and issues 😅)

image

Slack search (the first @ and # will create a drop down, but you can't do both with dropdowns.

image

So this is a feature I would love to have supported out the box for a search implementation...

And to make this work we need to start getting into Meta-programming. ie it would be easy to create a dropdown of @Collections in the search - as long as all collections were known/indexed.

Unless I have missed some key api for getting this info from Firestore I believe we would need to have a collection of collection-types containing the metadata of each of the collections in the system, perhaps including a list of sub-collections? essentially its doing stuff similar to counting the size of the collection over time.

It would be a similar strategy for tags - you would just assume that all documents in a collection can have an optional array field of tags. Then you would create a collection of tags that were available in the system.

If you had these two things in place you would be able to use the firestore query to do a search for a specific collection that contained a specific set of tags.

You could go further and say that all documents have to have a title and then you could do a in react-admin string filter on the title containing any of the key words you typed in to the search after having specified what collections and tags you wanted to search for.

Under the hood you would need to run one query/defined collection.

Noticing: If the @ and # feel to much like power user modes you could just use drop downs like toggl. And then have a text box area that said Filter instead of Search. In other words the query is created by the combination of collections + tags and the fuzzy search text is actually a fuzzy filter text.


Back to Meta Programming

So the search feature above is nice, but what I am really excited about is document types for a collection that change the way they are rendered in react-admin/custom app.

ie lets say I have a collection of records and each record declares its record type.

I can then develop a very different rendering rule per record type or per version of a record type, this would allow the data shape of a given object to change overtime without having to introduce default data into previous records.

You could use such a versioning system to drive an A/B ui testing system as well - perfect for developing MVPs.

The last idea I had for this was to build a dev portal for local development and then have the dev use react-admin to create document types that are saved to the development repo as json-schema/typescript interfaces. In theory as we have List guesser and Show guesser we should be able to render out a crud view immediately and if we want generate fake data based on the types.

This would lead to quite a nifty development experience as I could basically boot up my repo model some types into the system, deploy to firebase hosting, trigger the fake data function and tell the client to go to the url and login and interact with there model.

If you got this right - this could be fast enough to pair on them with developing their data objects in realtime

#IDreamADream

Update to React-Admin v3

React-Admin planning to release v3 this summer. Right now they are finalizing the alpha and started to preparing the migration guide.
Are there any plans to start migrating this package to work with v3? I did a quick check yesterday and there are some breaking changes that will be impacting this package.

https://github.com/marmelab/react-admin/releases

Next branch: https://github.com/marmelab/react-admin/blob/next/UPGRADE.md

TODOs

  • Removed RA realtime as per marmelab/react-admin#3908 (comment)
  • Implemented authProvider as object instead of function
  • authProvider.login method will now check for auth state change if no email and password is provided - enabling easy usage with third party Oauth firebase login flows (simply use useLogin without username and password OR specify '/' as the redirect URL as the checkAuth method will take care of making sure the user is logged in when redirecting)
  • Added example for usage with https://github.com/firebase/firebaseui-web-react resolves #34
  • Make react, react-admin and react-dom peerDependencies
  • Update demo project

Thanks to @simonberger (#67)

  • Update docs

Beta Version

We are getting closer to the stable version of this package which supports react-admin v3. Thanks to @simonbuerger he provided a pull request (#67) with the needed work.

To try the beta version of the package use the following to manually update the package in your project (for npm use npm install):

  • update react-admin to the lastest version
  • npm install / yarn add github:benwinding/react-admin-firebase#upgrade-to-react-admin-v3

Shared initialized firebase App instance

I am integrating react-filepond-firebase into react-admin-firebase and to share the initialized firebase.app from the react-admin-firebase library.

One approach would be to pass an initialized firebase object from the client layer that's setup in its own file, such as the example below:

store.js

import firebase from 'firebase'

const config = {
apiKey: "sadasdasasdasdasdasdasd-cqUU37c4",
authDomain: "asdasdasdasdasd.firebaseapp.com",
databaseURL: "https://asdasdasdasdas.firebaseio.com",
projectId: "asdasdasdasda",
storageBucket: "dadasdsadasdas.appspot.com",
messagingSenderId: "3423423423432432",
appId: "1:2343242342342:web:4234234234234"
};

const MyStore = firebase.initializeApp(config);

export default MyStore;

This file could be imported and MyStore could be passed to the React-Admin-Firebase Library, allowing additional access to the firebase app instance for realtime database and storage access.

  • or -

The initialized firebase app object that's in the react-admin-firebase library could be included and accessed after it's initialized.

Any assistance would be appreciated.

Cannot read property 'toDate' of null

I am getting this error when attempting to load records that contain a null value. To recreate seed a collection with a null value and attempt to load that collection into admin.

screenshot from 2019-03-02 11-46-54

Uncaught TypeError: Cannot read property 'toDate' of null
    at firebaseDataProvider.js:209
    at Array.forEach (<anonymous>)
    at firebaseDataProvider.js:206
    at Array.map (<anonymous>)
    at SafeSubscriber._next (firebaseDataProvider.js:204)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:247)
    at SafeSubscriber.next (Subscriber.js:176)
    at Subscriber._next (Subscriber.js:100)
    at Subscriber.next (Subscriber.js:69)
    at next (index.cjs.js:24898)
    at index.cjs.js:22534

Code Link

Error on create

Hi @benwinding, your job is awesome! react-admin-firebase works very fine!

When i create new doc i get this error on console:
The response to 'CREATE' must be like { data: { id: 123, ... } }, but the received data does not have an 'id' key. The dataProvider is probably wrong for 'CREATE'

I tried to redirect to list instead show, but the error ocurs and not redirect.

I struggled studing your code, but didn't have much success. I think the error occur because the method add on firebase is async and you return data without id.
I resolved the error passing a constant id, but obviously is not the right think to do.

File firebaseDataProvider.js
Method apiCreate changing line 157

return [2 /*return*/, { data: __assign({}, params.data) }];

return [2 /*return*/, { data: __assign({}, params.data, { id: "temp"}) }];

I am comming from C# and not have much experience with JS, i did any mistake using your lib or we have a issue?

Altering Firebase On Create

Hello, I'm trying to make a simple sign up app using react-admin and react-admin-firebase. My Firebase has a document of time slots, each with the timestamp and a bool whether it is filled or not. I have another document of signups, and am using the Create function to create new signups which contain a name and a timeslot. In Create for a new signup, it takes a ReferenceInput to a timeslot. I can get the timeslots to show up correctly in a SelectInput dropdown. If a user selects a timeslot and submits the form, I want to mark the bool in that timeslot in my Firebase to filled. Do I have to write a custom Save button, or how would I go about doing this? Or can you give an example of how to implement a handleSubmit function?

Importing 'firebase' explicitly imports ALL firebase components

I think this imports the entirety of firebase in the following source files:


I think the firebase team says it best:

It looks like you're using the development build of the Firebase JS SDK. When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use.

Multiple Image / File uploads from zero indexed array

Hi Ben,

Firstly just want to say a huge thank you for this library. Has enabled me to build out an admin panel for my firebase app really quickly.

I've noticed you've recently added file upload support for multiple files and it's working using the following format:

    <ArrayInput source="files">
        <SimpleFormIterator>
            <FileInput source="file" label="File">
                <FileField source="src" title="title" />
            </FileInput>
        </SimpleFormIterator>
    </ArrayInput>

Which stores the resulting data like this:

{
    files: [
        0: {
            file:  {
                src: "path_of_file",
                title: "name_of_file" 
           }
    ]
}

I was hoping instead to use the following format:

    <ImageInput source="images" label="Image" multiple={true}>
        <ImageField source="src" title="altText" />
    </ImageInput>
{
    files: [
        0: {
            src: "path_of_file",
            title: "name_of_file" 
        }
    ]
}

I'm going to have a go at creating a PR that will allow for both formats. Was there any reason you chose not to allow for this or were you not not aware of the usecase?

Typings not found

I have the same issue with react-admin so perhaps it's just something I missed but, simply running init steps and then importing ta-firebase in App.tsx gives me:

TS7016: Could not find a declaration file for module 'react-admin-firebase'. 

'/Users/rwoverdijk/projects/site/bluetour-admin/node_modules/react-admin-firebase/dist/index.js' implicitly has an 'any' type. 
  Try `npm install @types/react-admin-firebase` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-admin-firebase';`

To reproduce:

  1. yarn create react-app my-app --typescript
  2. yarn add react-admin
  3. Open App.tsx and import react-admin-firebase
  4. above ts error'.

How realtime works?

I'm wondering how realtime works. For example, I have a data collection call news. How to monitor it and get notified if there is a new update.

TypeError: Cannot read property 'app' of undefined

I cloned your project, followed it has it is on Your README. But I am getting this error this error

Cannot read property 'app' of undefined

src/providers/database/firebase/FirebaseWrapper.ts:34:14
On line 34 > if (options.app) {

src/providers/database/firebase/FirebaseWrapper.ts:16:33

On line 16 > this.app = ObtainFirebaseApp(firebaseConfig, options) as any;

The List goes on. What could be the issue and possible solution

I used the my firebase config like you specified, But still having the same error

Installation can't complete

please your support can't success for installation, I'm follow step by step user guide but can't success you can see picture below :

error

error 2

Is FirebaseRealTimeSaga working?

Hi there,

I am following the README to connect to real-time updates to the database using FirebaseRealTimeSaga, but when changing data in the Firebase console, my react-admin-firebase dashboard doesn't automatically update the data.

Also, to test this, I open two tabs in my browser: https://benwinding.github.io/react-admin-firebase-demo/#/comments

Then edit a comment or add a new one in of the tabs, expecting the data in the other tab would automatically update, but it doesn't happen.

Am I missing something?

Map custom field to id?

React-admin queries on the basis of the id of a record. My records instead use uid. I'd like to map uid to the id field. How might I accomplish this?

Here's this same question asked on the react-admin repo and the maintainer states that this should be handled by the REST client.

Custom Firebase/Firestore document name/key

Currently, react-admin-firebase uses Firebase random generated ID's for all database entries. For my users collection, I want to set the document ID from the params.email field.

firebaseDataProvider.TS currently uses 'collection.add()' for adding records.
For select cases it would be helpful to use connection.doc(someVar).set(params.data)

public async apiCreate( resourceName: string, params: IParamsCreate ): Promise<IResponseCreate> { const r = await this.tryGetResource(resourceName); log("apiCreate", { resourceName, resource: r, params }); const doc = await r.collection.add({ ...params.data, createdate: firebaseApp.firestore.FieldValue.serverTimestamp(), lastupdate: firebaseApp.firestore.FieldValue.serverTimestamp() }); return { data: { ...params.data, id: doc.id } }; }

Package not build when I fork your repository

I'm trying to migrate to react-admin v3. So I forked your repository. After that, when I yarn add https://github.com/zhouhao27/react-admin-firebase, the result is:

Screenshot 2019-10-31 at 10 55 46 PM

But when I yarn add react-admin-firebase, the result is:

Screenshot 2019-10-31 at 10 51 40 PM

Apparently my repository is not build when I added to my project. What is the possible reason? Thanks.

By the way, I didn't change anything yet after I forked your repository.

AUTH_GETCURRENT yields undefined

I have a startup saga that should execute when the user is logged in. I try to check this by using the AUTH_GETCURRENT action, but the result is always undefined.

lib/providers.ts

import { FirebaseAuthProvider, FirebaseDataProvider } from 'react-admin-firebase';
import addUploadFeature from './addUploadFeature';

const config = {
  /* ... */
};

export const dataProvider = addUploadFeature(FirebaseDataProvider(config));
export const authProvider = FirebaseAuthProvider(config);

lib/sagas.ts

import { crudGetList, showNotification } from 'react-admin';
import { authProvider } from './providers';

export default function* sagas() {
  const identity = yield authProvider('AUTH_GETCURRENT');
  console.log({ identity }); // { identity: undefined }
}

Sorting numbers

I have number of votes stored in firestore document as a number field votes: 123 but I'm unable to properly sort those values. Datagrid always looks at the first digit on the left side.

export const NewsList = (props: any) => (
  <List {...props} filters={<NewsFilter />}>
    <Datagrid>
      <NumberField source="votes" />
    </Datagrid>
  </List>
);

Example result of ASC sort:
12
132
1900
22
3
800
9

I even created custom field to cast it to number

const VotesField = (props: any) => {
  const numberOfVotes = {
    [props.source]: parseInt(props.record[props.source], 10)
  };
  
  return <NumberField {...props} record={numberOfVotes} />;
};

Still same result.

Firebase auth Username and Password prompt soft-lock-up

With a browser, chrome or firefox, that is not authenticated to the react-admin-firebase project, initially navigating to the sites base-url of http://localhost:3000, the browser is redirected to http://localhost:3000/#/login. When the username / Password screen is displayed, the Username and Password Fields as well as the sign in button are inactive, there is a wait 'circle' animation over the sign in button that never ends.

there is an error in the javascript console:

Error: Missing or insufficient permissions. index.cjs.js:409
FirestoreError index.cjs.js:409
fromRpcStatus index.cjs.js:6971
fromWatchChange index.cjs.js:7506
onMessage index.cjs.js:17650
startStream index.cjs.js:17561
getCloseGuardedDispatcher index.cjs.js:17611
newTail index.cjs.js:8990

Refreshing the browser window corrects the issue.

For reference here is the content of package.json
{
"name": "material-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-admin": "2.9.1",
"react-scripts": "3.0.1",
"@material-ui/core": "3.9.3",
"@material-ui/icons": "3.0.2",
"css-loader": "2.1.1",
"ra-data-fakerest": "2.6.0",
"ra-input-rich-text": "2.8.6",
"ra-language-english": "2.8.5",
"ra-language-french": "2.8.5",
"ra-core": "2.9.1"
},
"devDependencies": {
"@babel/runtime": "7.0.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

pagination doesn't seem to work with filter

Hi!
first of all thank you for making this awesome package. It makes my life a lot easier
But one thing i noticed using react-admin and react-admin-firebase is that when using filter, pagination seems to not working.

Below is an example captured from demo app (https://react-admin-firebase-1.web.app/#/posts)
image

There are total 6 and each page shows 5, hence there are total 2pages

image
but when i seach for t2, even though there are only one post that matches search keyword, the pagination still shows us there are 2 pages and if i click page 2, it just shows me an empty page.

shouldn't it show us only 1 page since the search result fits in one page?
Thank you !

ReferenceField for nested collections?

First thanks a lot for this beautiful creation.

I have a Users collection and within it an Addresses collection like the image below

issuetest

I'm trying to create a ReferenceField where I can get the "name" field in that user's address and be able to click through it and see all the user's addresses.

I'm guessing what I'm asking is that am I able to use paths? such as "/users/1/addresses/3" and retrieve those fields?

modify/restrict login

I have a bunch of users, only some should have access to the admin page, is there a way to do a check in a users collection for the admin flag before signing in?

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.