jsonreactjsobjectreact-reduximmutable.js

How to save redux store objects to external JSON file..?


I am having redux store as object key value pairs as given below:

{
  "appElements": {
    "layers": {
      "layer_1": {
        "scene": {
          "width": "100px",
          "height": "100px",
          "bgColor": "#aaaaaa",
          "bgImage": "http:bgimage1.png"
        },
        "items": {
          "yrgroih9": {
            "width": "100px",
            "x": "200px"
          },
          "qhy0dukj": {
            "width": "100px",
            "x": "200px"
          },
          "7lw2nvma": {
            "width": "100px",
            "x": "200px"
          }
        }
      }
    }
  }
}

I am using Immutable Js and the above data stored as Immutable Map data type into store.

Below image shows the state structure for better understanding: enter image description here

I need to save the above given store values into external json file, for example mysavedfile.json.

Code used in react reducer:

import { Map, fromJS, isImmutable } from 'immutable';

export default function images(state = new Map(), action) {
  switch (action.type) {

    case 'ADD_LAYERS':
      return fromJS({ appElements:action.data.appElements });

    case 'STATE_TO_JSON_FILE':
      console.log("state");
      //Here i need to do code to save state to external json file.

    default:
      return state
  }
}

How to achieve this..?


Solution

  • You won't be able to create a file directly on your computer's file system as this would be a huge security risk. You cannot do this from a web page using JavaScript.

    You could write a server side service to post your state to and it creates a file - you may then download the file or be content with where your server side stores it.

    You could alternatively create a file in memory and prompt a user download - for more answers like this see Create a file in memory for user to download, not through server