Coder Social home page Coder Social logo

react-admin-amplify's People

Contributors

dependabot[bot] avatar gabrielperales avatar mrhertal 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

react-admin-amplify's Issues

Enable buildAuthProvider to use Cognito user groups for external providers

We're using Cognito with Open ID Connect provider with Azure AD for authentication with our company email address. We therefore have an auto generated user group and it would be great if this could be used in the build auth provider function.

Is this possible currently, and if not do you have an idea of how it could be done (we'd be happy to contribute!).

Thanks!

Over-riding creation mutation

I have a react-admin resource of "users". For various reasons, my back-end is using both Cognito and DynamoDB to manage users. react-admin-amplify connects nicely to my Amplify backend and lists the users from the database table as I would expect.

I have created a custom mutation that has a lambda resolver which creates the Cognito user account, gets its sub value and then calls the standard CreateUser mutation to create the database record.

How can I have react-amplify-admin call a mutation other than the expected "CreateUser"?

Thanks ... Pete

Owner-Auth-Strategy

Hi,

when enabled owner auth in graphql schema I get problems with edit because the owner fields seems to be used as an input.

The error for example is: "The variables input contains a field name 'owner' that is not defined for input object type 'UpdateContactInput' "

Is there a way to ignore fields input fields like owner, createdAt, updatedAt?

I also wonder why null inputs are sent at create and edit.

Calling AdminQueries listUsers on resource cognitoUsers cause 500 errors from Amplify

<Resource
  name="cognitoUsers"
  list={ CognitoUserList }
  show={ CognitoUserShow }
/>

Does not work anymore via react-admin-amplify. Calls to amplify listUsers?limit=10&token= result in getting 500 errors with error message {"message":"STRING_VALUE can not be converted to an Integer"}.

Wondering if anyone having the same issue? Or am I doing something wrong here? Using AMAZON_COGNITO_USER_POOLS and AdminQueries already set up in Amplify. Other resources works fine.

Missing something fundamental when try to remove demo user

  1. If I comment out the authProvider.getIdentity section in App.js, I get the error,

LoginForm.js:36 Uncaught (in promise) TypeError: Cannot destructure property 'username' of 'userData.data.getUser' as it is null.
at getDemoUser (LoginForm.js:36:1)

and no fields for username/password render.


  1. If I comment out the 'getDemoUser()' and if(!demoUser) return null sections in LoginForm.js, I get a username/password field which then errors to

'TypeError: Cannot read properties of undefined (reading 'includes')
at children (App.js:133:1)'.

Appreciate any assistance or words of wisdom. Thank you.

Filtering using the $filter query parameter, to be able to search by multiple filters and improve flexibility.

We should also be able to use the $filters parameter in some filters so that multiple filters are possible.
Is there a workaround to implement such a thing? Currently I can only add a filter if there is a specific query for the filter, and its not possible to add multiple filters.

Maybe we can add two different types of filters, one that is query dependent (which is already there), and the other type only sets the $filter query parameters, which will be always visible...

How to display an uploaded file (link and icon) on the data table?

I want to add documents to the "Order" table. I've got the upload working on the create/edit forms but how to show on the data table. I've done some experimentation but am unsure if I have to use a and wrap a within it or only a will suffice. Tried both without success. Thank you!

AmplifyImageField in list view does not fetch images.

I use AmplifyImageField in a <List> component.
However, it does not fetch images in list view.
After going to show or edit page and getting back to list page, the only row I went to, shows images but the others does not show.

How should I resolve this problem? Thank you!

Unable to display users from DynamoDB in resource

import React from 'react';
import { Admin, Resource, ListGuesser } from "react-admin";
import { buildAuthProvider, buildDataProvider } from "react-admin-amplify";
import * as mutations from "./graphql/mutations";
import * as queries from "./graphql/queries";

function App() {
  return (
    <Admin 
      authProvider = {buildAuthProvider({ authGroups: [] })} 
      dataProvider = {buildDataProvider({ queries, mutations })}>
        <Resource name = "User" list={ListGuesser}/>
    </Admin>
  );
}

export default App;

Screenshot 2021-12-22 at 5 42 05 PM

Auth mode was setup using AMAZON_COGNITO_USER_POOLS, I am able to login and logout, see the user details on Cognito & DynamoDB.

Many to many input not working as expected

I have the following schema:

type Organization
    @model {
    id: ID!
    name: String!
    benefitPartners: [OrganizationBenefitPartner]
        @connection(keyName: "byOrganization", fields: ["id"])
}

type OrganizationBenefitPartner
    @model(queries: null)
    @key(
        name: "byOrganization"
        fields: ["organizationId", "benefitPartnerId"]
        queryField: "listOrganizationBenefitPartnerByOrganizationId"
    )
    @key(
        name: "byBenefitPartner"
        fields: ["benefitPartnerId", "organizationId"]
        queryField: "listOrganizationBenefitPartnerByBenefitPartnerId"
    ) {
    id: ID!
    organizationId: ID!
    organization: Organization! @connection(fields: ["organizationId"])
    benefitPartnerId: ID!
    benefitPartner: BenefitPartner! @connection(fields: ["benefitPartnerId"])
}

type BenefitPartner
    @model {
    id: ID!
    name: String!
    organizations: [OrganizationBenefitPartner]  @connection(keyName: "byBenefitPartner", fields: ["id"])
}

To edit the many to many relation I have the following:

import {
    ReferenceManyToManyInput,
    ManyToManyReferenceContextProvider,
} from '@react-admin/ra-relationships';

<Edit {...props} title="Benefit partners" transform={propsToBeUpdated}>
    <ManyToManyReferenceContextProvider>
        <SimpleForm>
            <TextInput source="name" />
            <ReferenceManyToManyInput
                source="id"
                reference="organizations"
                through="OrganizationBenefitPartner"
                using="benefitPartnerId,organizationId"
                fullWidth
                label="Organization"
                validate={required()}
            >
                <SelectArrayInput optionText="name" />
            </ReferenceManyToManyInput>
        </SimpleForm>
    </ManyToManyReferenceContextProvider>
</Edit>

I'm using the new ra-relationships-package.

  1. When opening the edit-screen I don't see the values for the many to many relation. But if I click on the dropdown, the values I can choose from actually shows up and have the correct data. No idea why it doesn't appear in the input as the benefit partner has organizations.
  2. When saving the content I get the following error message: Could not find query createOrganizationBenefitPartne. Which should be 'createOrganizationBenefitPartner'. Does it try to un-pluralise the table by removing the last letter?

Anything I'm missing here? Some pointers would be much appreciated

Unable to remove resource reactadminamplifydem9cde0abfPreAuthentication

Hi,

I tried to setup and run the demo application and followed the setup instruction as mentioned in the ReadMe.

I am unable to remove resource reactadminamplifydem9cde0abfPreAuthentication.

When I try to run the demo, I land on the login screen, I am not getting redirected to dashboard after logging in.

Note: I created a new user in the Cognito User Pool (Confirmed User)

How to alter `getQueryName` and `getQueryNameMany`?

Hi @MrHertal !

I realized in latest amplify it generates queries like: dataPointsByMetricID instead of listDatapointsByMetricId which is generated via getQueryName and getQueryNameMany functions.

Although, there is no way to alter those functions, and DataProvider is not exported nor its parts.

There are two options, which might be helpful:

  1. Make DataProvider customizable including getQueryName
  2. Update getQueryName according to recent updates

Also, I would suggest not using getQueryName and similar functions as class methods preferring simple functions.

AWSS3Provider - ensure credentials error No Auth module registered in Amplify

I've follow the Storage implementation but when i select a file from AmplifyFileInput or AmplifyImageInput i see this error in console:
AWSS3Provider - ensure credentials error No Auth module registered in Amplify
No credentials

The storage is not public (require valid user) but i'm logged into react-admin with "Admin" user and i see all other data
How can i do?

TypeError: Cannot read properties of undefined (reading 'nextToken')

There was an error using filter using query. When I submit the code, "TypeError: Cannot read properties of undefined (reading 'nextToken')" error occured. What's the problem?

  • Schema
type B2BProduct
  @model
  @auth(
    rules: [
      { allow: public, operations: [create, update, delete, read] }
      { allow: groups, groups: ["user", "adminUser"] }
    ]
  )
  @key(name: "byCode", fields: ["code", "id"], queryField: "B2BProductsByCode") {
  id: ID!
  thumbImage: S3Object!
  price: Int!
  productOption: [Option]!
  quantity: Int!
  eventText: String
  code: Int!
  is_del: Int!
  user_id: String!
  product_id: String!
}

  • queries
export const b2BProductsByCode = /* GraphQL */ `
  query B2BProductsByCode(
    $code: Int
    $id: ModelIDKeyConditionInput
    $sortDirection: ModelSortDirection
    $filter: ModelB2BProductFilterInput
    $limit: Int
    $nextToken: String
  ) {
    B2BProductsByCode(
      code: $code
      id: $id
      sortDirection: $sortDirection
      filter: $filter
      limit: $limit
      nextToken: $nextToken
    ) {
      items {
        id
        thumbImage {
          bucket
          region
          key
        }
        price
        productOption {
          name
          contents {
            name
            contents {
              name
              contents {
                name
              }
            }
          }
        }
        quantity
        eventText
        code
        is_del
        user_id
        product_id
        createdAt
        updatedAt
      }
      nextToken
    }
  }
`;

React Admin Amplify not being able to authenticate nor load content.

Hi,

I am trying to get this tool working with my Amplify instance, but I am having the following error:

"next-dev.js?3515:25 [ERROR] 54:58.499 AuthError -
Error: Amplify has not been configured correctly.
The configuration object is missing required auth properties.
This error is typically caused by one of the following scenarios:

        1. Did you run `amplify push` after adding auth via `amplify add auth`?
            See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information

        2. This could also be caused by multiple conflicting versions of amplify packages, see (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js) for help upgrading Amplify packages."

does it has to do with the line in your documentation:
"You will need the configuration file aws-exports.js of your Amplify backend, so that react-admin can connect to your API." ?

I am using nextjs

Can create a object but can't edit ReferenceInput input

I've create a simple crud stack... i can create a Pill object but can't update, here is my code:

export const PillList = (props) => (
  <List {...props}>
    <Datagrid>
      <TextField source="title" />
      <TextField source="description" />
      <ReferenceField
        source="type.id"
        label="Type"
        reference="types"
        link="show"
      >
        <TextField source="title" />
      </ReferenceField>
      <EditButton />
      <DeleteButton />
    </Datagrid>
  </List>
);

export const PillCreate = (props) => (
  <Create {...props}>
    <SimpleForm>
      <TextInput source="title" />
      <TextInput multiline source="description" />
      <ReferenceInput label="Type" source="pillTypeId" reference="types">
        <SelectInput optionText="title" />
      </ReferenceInput>
    </SimpleForm>
  </Create>
);

export const PillEdit = (props) => (
  <Edit {...props}>
    <SimpleForm>
      <TextInput disabled label="Id" source="id" />
      <TextInput source="title" />
      <TextInput multiline source="description" />
      <ReferenceInput label="Type" source="type.id" reference="types">
        <SelectInput optionText="title" />
      </ReferenceInput>
    </SimpleForm>
  </Edit>
);

This is schema.grapql:

type Pill
  @model
  {
  id: ID!
  title: String
  description: String
  typeID: ID!
  type: Type @connection(fields: ["typeID"])
}

type Type
  @model
  {
  id: ID!
  title: String
}

If i use pillTypeId as source of ReferenceInput into Edit form (like Create form that work fine), when edit an item i can't see the value into select.
If i use type.id as source of ReferenceInput into Edit form, when edit an item i can see the right value into select.

Both of cases i can't update the data and return this error:

"The variables input contains a field name 'type' that is not defined for input object type 'UpdatePillInput' "

Where is the problem? In my schema?

How can i do?
Thanks

Cannot read properties of undefined (reading 'nextToken')

I have a Create view that contains a ReferenceArrayInput and AutocompleteArrayInput, I would like this "dropdown"'s items to be filtered.

In this case the dropdown shows a list of Careers, however I only want Careers that have a flag, called relatedCareer, equal to 1 to show up in dropdown. The query for this is below

<ReferenceArrayInput
 label="Related Careers"
 source="relatedCareers"
 reference="careers"
 filter={{ flaggedAsRelatedCareer: { relatedCareer: 1 } }}
>
 <AutocompleteArrayInput />
</ReferenceArrayInput>
query FlaggedAsRelatedCareer(
      $relatedCareer: Int = 1
      $limit: Int
      $nextToken: String
    ) {
    listCareers(filter: {relatedCareer: {eq: $relatedCareer}}, limit: $limit, nextToken: $nextToken) {
      items {
        id
        name
        relatedCareer
      }
      nextToken
    }
  }

In the Network tab of the console I can see the data being returned by the query is what I'm expecting:

data: 
 listCareers: 
  items: 
   0: {id: "related-career-1-id", name: "Related Career 1", relatedCareer: 1}
  nextToken: null

However I get the following error:

index.js:1 TypeError: Cannot read properties of undefined (reading 'nextToken')
    at DataProvider.<anonymous> (DataProvider.ts:127)
    at step (tslib.es6.js:102)
    at Object.next (tslib.es6.js:83)
    at fulfilled (tslib.es6.js:73)

Is there something I am missing here?

How to add subscriptions?

Any words of wisdom w.r.t. adding subscriptions? I want to connect out-of-band notifications about dynamodb changes to provide real time notifications.

I am not experienced digging into node_modules. Thanks in advance.

undefined error on first query

I've followed AWS's Amplify tutorial as well as your and react-admin tutorials.

Here is my App.js

import { Amplify } from "@aws-amplify/core";
import React from "react";
import { Resource, ListGuesser, Admin } from "react-admin";
import { buildDataProvider } from "react-admin-amplify";
import awsExports from "./aws-exports";
import * as mutations from "./graphql/mutations";
import * as queries from "./graphql/queries";

Amplify.configure(awsExports); // Configure Amplify the usual way

function App() {
    return (
        <Admin // Replace the Admin component of react-admin
            dataProvider={buildDataProvider({ queries, mutations })}
        >
            <Resource name="todos" list={ListGuesser} />
        </Admin>
    );
}

export default App;

In my models I have

type Todo @model {
  id: ID!
  name: String!
  description: String
}

However, upon running the application http://localhost:3000/#/todos I get no results, the loader spinner keeps spinning and there is a following message on console:

Screen Shot 2021-01-06 at 19 14 34

how to handle with `Refresh Token has expired`?

When I ran development server and tried to login, I got this error.
My settings about token expiration date is set to default. (So, refresh token expiration date is 30 days). However It's been shorter than 30 days since I last logged in.

Could anyone show me how to deal with this problem??

Thank you!

Many to many relation

Hi.

I have a typical product, category model.

Here are my models

type Product
  @model
  @auth(
    rules: [
      { allow: public, operations: [create, update, read], provider: apiKey }
      { allow: groups, groups: ["admin"] }
    ]
  )
  @key(
    name: "byRequest"
    fields: ["requestID", "id"]
    queryField: "productsByRequest"
  ) {
  id: ID!
  requestID: ID!
  name: String!
  reviewsCount: Int!
  url: String!
  ratings: Int
  items: [Item]!
  categories: [ProductCategory]!
    @connection(keyName: "ProductCategories", fields: ["id"])
}

type ProductCategory
  @model(queries: null)
  @auth(
    rules: [
      { allow: public, operations: [create, update, read], provider: apiKey }
      { allow: groups, groups: ["admin"] }
    ]
  )
  @key(
    name: "ProductCategories"
    fields: ["productID", "categoryID"]
    queryField: "categoriesByProducts"
  )
  @key(
    name: "CategoryProducts"
    fields: ["categoryID", "productID"]
    queryField: "productsByCategories"
  ) {
  id: ID!
  productID: ID!
  categoryID: ID!
  product: Product! @connection(fields: ["productID"])
  category: Category! @connection(fields: ["categoryID"])
}

type Category
  @model
  @auth(
    rules: [
      { allow: public, operations: [create, update, read], provider: apiKey }
      { allow: groups, groups: ["admin"] }
    ]
  ) {
  id: ID!
  name: String!
  link: String!
  products: [ProductCategory]!
    @connection(keyName: "CategoryProducts", fields: ["id"])
}

And I want to refer to categories in

<List {...props}>
...
        <ReferenceManyField
          reference="categories"
          label=""
          target="categoriesByProducts.productID"
          fullWidth
        >
<Datagrid>
...
</Datagrid>

</List>

I checked that fetching is successfully executed but there is nothing to show.

Could you give me an idea how to show fetching result?

Manage users in Cognito using admin actions

Admin actions allows us to quickly generate an API for managing Cognito users and groups. The goal of this issue is to discuss how we could make react-admin-amplify communicate with that API.

The way I see it right now is:

  • Define a resource name like cognitoUsers
  • Edit the data provider so when it sees that resource name is cognitoUsers, it calls the admin API instead of the GraphQL API.
  • Same thing with cognitoGroups

From here, we can easily list users and groups and display one user and one group.

In order to avoid people to always look for available fields we could create 4 components:

CognitoUserList
CognitoUserShow
CognitoGroupList
CognitoGroupShow

and since there is no update or delete, we could create two resources: CognitoUserResource and CognitoGroupResource that are only implementing list and show.

That would be a good start. But we could go further 🙂

What would be nice is to also create something like react-admin ShowButton, but the actions would be for each user:

confirmUserSignUp
disableUser
enableUser

other actions like addUserToGroup are more complex because they require a form, so we will have to create a custom route that is displaying a form and manage this form submit. I did something similar in a project and could do this easily.

cognito keep return no current user

I cloned your demo with amplify init --app 'the link', and after adding the cognito user groups in my aws cognito console, I failed to login and it keeps returns something like 'no current user', failed to get user pool etc...Do you know why it happens? Thanks.

Help wanted: Login form customisation

I would like to customise the look of the login page but I can't see it anywhere in the documentation. Would you be able to point me to the correct place or advise on how I can do this. Thanks

1:1 relationships

As there's no example on the demo code I've tried to get one to one relationships working. There is no problem when you only try to create entries in the table using the standard create component. But if you try to update a record there throws an error saying "The variables input contains a field name 'ABC' that is not defined for input object type '123' ". As mentioned, with exactly the same schema creations are possible which uses ABC at 123-type.

the schema looks like this:

@model
{
id: ID!
something: String
}

type 123
  @model
{
id: ID!
anything: String
abcID: ID
abc: abc! @connection(fields: ["abcID"])
}

Sort list and filter by connection field

Hi,
excuse me for opened a new issue but i can't enable sorting... i've follow documentations and this is my new code but don't work fine... i see the column arrow asc and desc but the data are not sorted...
I've to display a list of data (Pill items in my case), enable sort column by delay field (a numeric field) and add a simple filter by type (type is a connection, not a real field)... can you give me an functional example for do it? I think this can bu usefull for other people...

Thanks

type Pill
  @model
  @key(name: "byOrder", fields: ["id", "order"], queryField: "pillsByOrder")
  @auth(
    rules: [
      {
        allow: groups
        groups: ["Admin"]
        operations: [create, read, update, delete]
      }
      { allow: groups, groups: ["Client"], operations: [read] }
    ]
  ){
  id: ID!
  title: String
  order: Int!
  description: String
  type: Type @connection(name: "PillType")
  createdAt: String
}

type Type
  @model{
  id: ID!
  title: String
  pills: [Pill] @connection(name: "PillType")
}

export const PillList = (props) => (
  <List {...props}>
    <Datagrid>
      <TextField source="title" sortBy="pillByTitle" sortable={true}/>
      <TextField source="description" />
      ```

Getting access to Amplify / Cognito Auth.currentAuthenticatedUser()?

AuthProvider is an awesome wrapper. Yet, I am unsure how to get the details of the current logged -in user for further manipulation (triggering in-app messages, emails, etc)?

I noted the graphql query for 'demo' in the '17 patterns example', but that already has a 'demo user' to reference.

Would appreciate any advice.

How to limit user of a certain merchant group access to own resources?

I just encountered another issue using the library.
My use case is to handle multi-merchant business - each user account (admin) belongs to a merchant group.
How can I do something like listing only the records belong to each merchant user, which means a merchant cannot see other merchant's resources(such as transaction, employee info, user info etc?)

I have already integrated my cognito users signup with dynamoDB and also login info stored in redux, so now I can fetch user info, user groups and query dynamoDB to get the merchant group that user belong to. The problem is now with the query...any suggestion?

[Bug]: The variables input contains a field name 'modules' that is not defined for input object type 'UpdateRoomInput'

I am getting this error while updating the form of modules resource.

Here's my schema

type Room
@model
@key(name: "customerIndex", fields: ["customerId"], queryField: "listRoomsByCustomerId")
@auth(rules: [
  { allow: groups, groupsField: "customerId" },
  { allow: groups, groups: ["Admin"] }
]){
  id: ID!
  customerId: ID! # This will be retrieved by scanning
  name: String!
  type: RoomType!
  modules: [Module] @connection(keyName: "byRoom", fields: ["id"])
}

type Module
@model
@key(name: "byRoom", fields: ["roomId"], queryField: "listModulesByRoomId")
@auth(rules: [
  { allow: groups, groupsField: "customerId" },
  { allow: groups, groups: ["Admin"] }
]){
  id: ID! # This will be retrived by scanning
  roomId: ID!
  customerId: ID!
  room: Room @connection(fields: ["roomId"])
  appliances: [Appliance] @connection(keyName: "byModule", fields: ["id"])
}

And here's my RoomEdit script:

function RoomEdit(props) {
    return (
        <RA.Edit {...props}>
            <RA.TabbedForm>
                <RA.FormTab label="Summary">
                    <RA.TextInput disabled label="Id" source="id"/>
                    <RA.TextInput disabled label="Customer ID" source="customerId"/>
                    <RA.TextInput label="Name" source="name"/>
                    <RA.SelectInput
                        source="type"
                        choices={[
                            {id: "LivingRoom", name: "Living Room"},
                            {id: "BedRoom", name: "Bed Room"},
                            {id: "Kitchen", name: "Kitchen"},
                            {id: "BathRoom", name: "BathRoom"}
                        ]}
                    />
                </RA.FormTab>
                <RA.FormTab label="Modules">
                    <RA.ReferenceManyField reference="modules" target="roomId" addLabel={false}>
                        <RA.Datagrid>
                            <RA.TextField source="id"/>
                            <RA.DateField source="createdAt"/>
                            <RA.DateField source="updatedAt"/>
                            <RA.EditButton/>
                        </RA.Datagrid>
                    </RA.ReferenceManyField>
                </RA.FormTab>
            </RA.TabbedForm>
        </RA.Edit>
    );
}

export default RoomEdit;

I am not sure why am I getting this error. Am I doing anything wrong or Is it a bug in the library?

How to custom error message from Server return?

I have a delete function, that will validate something before delete. So when admin click "Delete", I'd like to display the message inside errors object of GraphQL to let admin know what's wrong (instead of default message "Server communication error"), So how I do that? thx.

How do I use the ascending and descending order?

Excuse me, I read the document in react-admin-amplify and implemented the sort, but the sort is not working properly. In addition, how can I distinguish ascending and descending order when using sorting?

All I want is to be sorted in code order

Thank you.

type B2BProduct
  @model
  @auth(
    rules: [
      { allow: public, operations: [read] }
      { allow: groups, groups: ["user", "adminUser"] }
    ]
  )
  @key(name: "byCode", fields: ["code", "id"], queryField: "b2BProductsByCode") {
  id: ID!
  thumbImage: S3Object!
  price: Int!
  productOption: [Option]!
  quantity: Int!
  eventText: String
  code: Int!
  is_del: Int!
  user_id: String!
  liveProductId: String
  product_id: String!
}
import React, { useState } from 'react';
import {
  Datagrid,
  DateField,
  EditButton,
  List,
  NumberField,
  ShowButton,
  TextField,
  TextInput,
  ReferenceField,
  ArrayField,
  ChipField,
} from 'react-admin';
import { AmplifyFilter } from 'react-admin-amplify';
import { Pagination } from '../Pagination';

const defaultQuery = 'listB2BProducts';

const B2BProductFilter = props => (
  <AmplifyFilter {...props} defaultQuery={defaultQuery}>
    <TextInput source='b2BProductsByCode.code' label='Code' alwaysOn resettable />
  </AmplifyFilter>
);

export const B2BProductList = props => {
  const [query, setQuery] = useState(defaultQuery);
  return (
    <List {...props} sort={{ field: 'code', order: 'DESC' }} filters={<B2BProductFilter setQuery={setQuery} />} pagination={<Pagination />} >
      <Datagrid>
        <NumberField label='Tiền hàng' source='price' />
        <TextField source='eventText' label='eventText' />
        <ArrayField source='productOption' label='Tùy chọn'>
          <Datagrid>
            <ChipField source='name' label='Tùy chọn' />
            <ArrayField source='contents' label='tùy chọn chi tiết'>
              <Datagrid>
                <ChipField source='name' label='tùy chọn chi tiết' />
              </Datagrid>
            </ArrayField>
          </Datagrid>
        </ArrayField>
        <NumberField label='code' source='code' sortable={query === 'b2BProductsByCode'} textAlign='center' />
        <ReferenceField label='Tên sản phẩm' source='product_id' reference='products'>
          <TextField source='name' />
        </ReferenceField>
        <ReferenceField label='User' source='user_id' reference='users'>
          <TextField source='name' />
        </ReferenceField>
        <DateField source='createdAt' />
        <DateField source='updatedAt' />
        <ShowButton />
        <EditButton />
      </Datagrid>
    </List>
  );
};

Filter & Sort

Can I sort or filter post receiving data i.e. without using custom queryFields?

On filter - how can I use wildcards?

On sort, it seems that we can't sort on the primary key, only the secondary key. Is that right? Is that an Appsync limitation or just the way sorts currently work?

Graphql pluralization for Edit: useGetOne() relies on the Redux store

I have an AWS Amplify graphql api model:

type Category @model {
  id: ID!
  name: String!
  colour: String!
  careers: [Career] @connection(keyName: "byCategory", fields: ["id"])
  questions: [Question] @connection(keyName: "byCategory", fields: ["id"])
}

My list component works 100% out of the box using what ListGuesser provides.

For Create, using a very basic Create form:

const CreateCategory = (props) => (
  <Create
    {...props}
  >
    <SimpleForm>
      <TextInput source="name" />
      <TextInput source="colour" />
    </SimpleForm>
  </Create>
);

When I try to save the form data, it. produces an error:

Could not find query createCategorie

Seems like a classic error in pluralization, but. inspecting the code of this lib or the graphql lib used yielded no information to me. I updated the Create:

const CreateCategory = (props) => (
  <Create
    // eslint-disable-next-line react/jsx-props-no-spreading
    {...props}
    /* this is weird, but I think translation is messing with us.
    * Since the lib was trying to hit createCategorie
    * (mis-singularization of categories -> category.)
    * when I passed "category" as the resource, it incorrectly dropped the y at the end.
    */
    resource="categoryy"
  >
    <SimpleForm>
      <TextInput source="name" />
      <TextInput source="colour" />
    </SimpleForm>
  </Create>
);

And it worked.
Moving on I expected the same to be required for Edit but alas it did not work.
My Edit component:

const EditCategory = (props) => (
  <Edit
    {...props}
  >
    <SimpleForm>
      <TextInput source="name" />
      <TextInput source="colour" />
    </SimpleForm>
  </Edit>
);

This produces the some message that Create produced:

Could not find query getCategorie

So I added the resource, first just with one y:

const EditCategory = (props) => (
  <Edit
    // eslint-disable-next-line react/jsx-props-no-spreading
    {...props}
    /* this is weird, but I think translation is messing with us.
    * Since the lib was trying to hit createCategorie
    * (mis-singularization of categories -> category.)
    * when I passed "category" as the resource, it incorrectly dropped the y at the end.
    */
    resource="category"
  >
    <SimpleForm>
      <TextInput source="name" />
      <TextInput source="colour" />
    </SimpleForm>
  </Edit>
);

Which yields:

useGetOne.js:43 Uncaught Error: No <Resource> defined for "category". useGetOne() relies on the Redux store, so it cannot work if you don't include a <Resource>.

Adding another y to the resource in an attempt to hack it:

const EditCategory = (props) => (
  <Edit
    // eslint-disable-next-line react/jsx-props-no-spreading
    {...props}
    /* this is weird, but I think translation is messing with us.
    * Since the lib was trying to hit createCategorie
    * (mis-singularization of categories -> category.)
    * when I passed "category" as the resource, it incorrectly dropped the y at the end.
    */
    resource="categoryy"
  >
    <SimpleForm>
      <TextInput source="name" />
      <TextInput source="colour" />
    </SimpleForm>
  </Edit>
);

Which produces the same error for the updated resource name:

useGetOne.js:43 Uncaught Error: No <Resource> defined for "categoryy". useGetOne() relies on the Redux store, so it cannot work if you don't include a <Resource>.

Any help would be greatly appreciated.

S3 object support?

Does, or will, this support image/document/etc. upload and pull from S3, as Amplify does?
Thanks for the excellent work, by the way!

How we can use searchable methods?

As per documentations try sorting based on keys but its not working. Mainly we need ...

  1. Multiple keys
  2. Default filter based on one of key

Then only keys method available for sort.

Query fails when schema contains types with more than "one word", capitalised as per AWS standard convention (e.g. DashboardItems)

with the following Amplify graphql schema:

type DashboardItem
  @model
  @key(
    name: "byName"
    fields: ["name", "id"]
    queryField: "dashboardItemsByName"
  ) {
  id: ID!
  name: String!
}

Even though the default query variable is cased correctly:

const defaultQuery = "listDashboardItems";

The following error appears in the console:

Could not find query listDashboarditems

I'm assuming the case is being modified somewhere in the dataproivider?

How to display active or inactive drivers using AmplifyFilter

Hi @MrHertal,

Thank you for the great work on react-admin-amplify. And I am currently building a prototype application based on it.

I was wondering if you could shed some lights on how to implement a filter of dropdown box that can be used to list only the active, inactive, or all drivers respectively for the following Driver type,

type Driver
  @model(timestamps:{createdAt: "createdOn", updatedAt: "updatedOn"})
  @auth(rules: [
    {allow: private}
  ])
  @key(name: "byFirstName", fields: ["firstName", "id"], queryField: "driversByFirstName")
  @key(name: "byLastName", fields: ["lastName", "id"], queryField: "driversByLastName") {
  id: ID!
  firstName: String!
  lastName: String!
  startDate: AWSDateTime!
  endDate: AWSDateTime!
}
  • the query should return all the drivers by default
  • if the active option is selected in the dropdown filter, the query should return all active drivers where the current date is between the startDate and endDate, i.e., startDate < currentDate < endDate
  • if the inactive option is selected in the dropdown filter, the query should return all inactive drivers where the current date is outside the startDate and endDate, i.e. currentDate < startDate || current > endDate

Is the above filter currently supported in react-admin-amplify? If not, what would be the best way to have this implemented?

Thanks in advance
Ray

Use with DataStore client

Has anybody successfully used this with the Amplify DataStore client? It doesn't seem to detect changes made by React Admin in my mobile client. I guess the reason is that _version and _lastChangedAt might not be set automatically.

Would it be sufficient to simply set both when updating a record? Did anybody get this to work properly?

Update is trying to set properties it shouldn't (can't)

I have a number of @connection items in the graphql and they are obviously getting into the data (which is fine). However, when I edit a record, it seems to be trying to set all the properties, not just the changed ones, or even editable ones.

I guess the easy fix is to only update the properties that were specified in the edit view if we can't tell what changed?

Bruce

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.