1

I have a django API which describes resources using snake_cased json. I also have a React app which consumes the API. I could map the snakecased properties in different locations, ex, in the API renderer, or at the component level.

Is there a best practice on where to apply this transformation?

Sua Morales
  • 816
  • 8
  • 20

2 Answers2

2

You can build a wrapper around the API functions which you consume. Use a helper library like humps to convert the requests and responses payloads. Try to keep it as close the API calling as possible.

import {camelizeKeys, decamelizeKeys} from 'humps';

$.post("/postendpoint",
    decamelizeKeys({
        fooBar: "zoo",
    }),
    function (data, status) {
        doSomething(camelizeKeys(data));
    }
);
ztadic91
  • 2,526
  • 1
  • 11
  • 17
1

Doing it at the client API level keeps the state cleaner for your components and requiring less iteration/function calls than if you say apply the transformation in multiple components. Because this can lead to unnecessary rendering because of how React components render by default (each time props or state has changed).

Then again you could also handle it at your top-level component and make sure with shouldComponentUpdate that no unnecessary rendering occurs, but that feels messy.

TL;DR let the transformed API data trickle down to your components to avoid confusing code and unnecessary re-rendering

Emil Hernqvist
  • 118
  • 1
  • 6