3

I am trying to directly map API response to my Redux-Orm models. I have two models:

Product hasMany ProductProperties

ProductProperty belongsTo Product

The API response I receive is:

{
  products: [
    {name: 'P1', id: 1},
    {name: 'P2', id: 2}
  ],

  product_properties: [
    {name: 'Test1', id: 10, product_id: 1},
    {name: 'Test2', id: 11, product_id: 1},
    {name: 'Test3', id: 12, product_id: 2}
    {name: 'Test4', id: 13, product_id: 2}
  ]

}

I can tweak the API response to match with the redux-orm.

My Question is:

I want to avoid doing ProductProperty.first().set({product: Product.first}) -- That is I don't want to set the associations (child records) explicitly and have redux-orm infer them automatically.

Is there some way I can specify the foreign key that redux-orm can look for?

Nerve
  • 6,463
  • 4
  • 29
  • 29

1 Answers1

1

What I recommend to you is to use a json api standard for your API.

That way, in your API return, your products would have a relationships key that will help you map it to the included product_properties. Something like:

{
  data: [
    {
      type: 'product',
      id: 1,
      name: 'P1',
      relationships: [
        product_property: [
          {
            data: {type: 'product_property', id: 10}
          },
          {
            data: {type: 'product_property', id: 11}
          }
        ]
      ]
    },
    {
      type: 'product',
      id: 2,
      name: 'P2',
      relationships: [
        product_property: [
          {
            data: {type: 'product_property', id: 12}
          },
          {
            data: {type: 'product_property', id: 13}
          }
        ]
      ]
    }
  ],

  included: [
    {type: 'product_property', name: 'Test1', id: 10},
    {type: 'product_property', name: 'Test2', id: 11},
    {type: 'product_property', name: 'Test3', id: 12}
    {type: 'product_property', name: 'Test4', id: 13}
  ]
}

That way, it would be much easier for you to make a standard API parser that would map your json api resources to your redux-orm store. You create a redux-orm resource for each product and each product_property. Than you loop over product relationships and link them.

Hope that would help.

Best

guillaumepotier
  • 7,369
  • 8
  • 45
  • 72
  • That makes sense. But, what I am looking for is: Is there some way I can organize my API response so that I don't have to loop over relationships? Like: I specify the foriegn key, association name and association model and redux-orm takes from there? – Nerve Jun 19 '17 at 14:10
  • I don't think this is possible. Redux-orm don't do everything by its own. You'll have to create parents and relationships, and then link them together. This is your duty to correctly create and link entities together from your API response. *then*, redux-orm will help you retrieve, query them and display them. But you'll have some work to do at the input from your api! – guillaumepotier Jun 19 '17 at 14:29