react-router data router submit nested json data

This topic is a hot one and has resulted in a long thread: https://github.com/remix-run/remix/discussions/1959

and remix discord questions lik: "how can i use useFetcher to submit a big nested JSON object to an action (via POST without a backing <fetcher.Form> component)? it seems like fetcher.submit only accepts Record<string, string>."

Answer: "You can JSON.stringify the data and JSON.parse it on the action"


Support to submit json data was added to react-router DataRouter, but only un-nested json e.g. { name: "jane", hair: "purple" }

But not nested: { name: "jane", hair: "purple", address: { street: " 1 Main St."} }

Which is the key missing piece.


So you can now do this

    fetcher.submit(

      { action: 'save', name: "jane", hair: "purple"  },

      { method: 'post', encType: "application/json", action: "/" }

    );


 and in the action function get json from the request like so

   const myJsonData = await request.json();


...but not for nested json, try with nested json will result in a exception on submit.


The only option currently if you have to deal with nested json in react-router DataRouter is to stringify it like so for example:

    fetcher.submit(

      { action: 'save', data: JSON.stringify(values) },

      { method: 'post', encType: "application/json", action: "/" }

    );


and in the action function unstringify it:

    const formData = await request.formData();

    const formDataAsObject = Object.fromEntries(formData);

    const formAction = formDataAsObject.formAction;

    const formData = JSON.parse(formDataAsObject.data)


* don't forget try/catch for possible parse exception


I get the philosophical resistance to supporting json as Ryan discussed in that linked thread. But it's also the case that sometimes the data model is complex and nested. The BE returns nested json and expects nested Json posted back. The UX reflects that nesting with accordions etc. So the Frontend has to deal with nested json.

And, support has already been added for un-nested json so why not nested json? Sorry but you're already "crossed the rubicon" on json.


I also understand its an option to try structure your  app differently. HTML Form natively supports nesting. However your apis may also have to change to take partial payload e.g. on a multipage flow where could save on each step. But the Frontend could end up fighting the nature of the problem domain. Mismatches like that can be a source of confusion, cognitive overhead and bugs.


Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

My Reading Lists