React Hack: Export & Import State

Jordan Panasewicz
2 min readAug 30, 2021

Following up on my last post — React Hack: persisting data using local storage.. I wanted to explore more ways improve user experience and optimize applications for user convenience. This time is the idea that a user can export and import a file (app state as JSON).. This is definitely a bit of an interesting concept, as it will essentially allow a front end application to store data… in the sense that as a user of an application you can perform a bunch of actions, even click a “save” button, but instead of saving that data to a database, that object (or whatever it may be that your saving) get’s put into a file, that you can later load back into the application and pick up where you left off…

There are several ways to go about this, but from my research I found the simplest to be a package called “exportFromJSON”. (Click the name to go to their package page and check out their basic usage.)

So obviously there are a couple of steps here, and I’m not going to get into state management or form building or click handling or anything like that.. the TWO main steps are simply an export function that exports application state as a JSON file, and an import function that imports a JSON file and sets state..

In our example, state is going to be managed all in one object cleverly called “state”.

  1. Export function:
const exportFile = () => {   const data = [{state: state}];   const fileName = "application-state";   const exportType = exportFromJSON.types.json;   exportFromJSON({ data, fileName, exportType });};

Here you can see what we are doing is creating an object of state as a variable called “data”. We can then give the export a name, I simply went with “application-state”, but you might want to use something more related to your app. Finally we choose a file type, and call the exportFromJSON function with those 3 things as arguments. This will trigger a direct download of the application state as a JSON file to the users computer!

2. Import function:

const importFile = (file) => {  if (file) {    file    .text()    .then((data) => JSON.parse(data))    .then((data) => {    setState(data[0].state);    });   }};

The import function requires a file input, and then we JSON.parse that file, and set state to the data it was parsed from.

The overall concept here is fairly simple, but obviously will change based on how you are managing state. The key concept is a form that prompts the user to upload a file (a previously exported JSON file at that), and then parses the data, and sets it to application state. As with any functionality like this, data structures and data management come into play, but this shouldn’t take too long to figure out. Good luck, and use Google if you get stuck!

Cheers, I’ll see you again soon!

--

--

Jordan Panasewicz

Denver, CO based. Software Sales turned Software Engineer.