0

I'm referring to this post (Write to a text or JSON file in react with node).

I got the exact problem so I tried out the solutions. I don't understand the solutions very well. I spent a lot of time doing by trial and errors. For example, in this solution:

const handleSaveToPC = jsonData => {
  const fileData = JSON.stringify(jsonData);
  const blob = new Blob([fileData], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = 'filename.json';
  link.href = url;
  link.click();
}

Where should I put this code? The variable "handleSaveToPC" is declared but not used. How should I use it? I show my App.js and index.js files below. My goal is to write the contactsData array to a local json or text file. I do appreciate if anyone guide me exactly what I have to do. Thank you so much.

App.js

import React, { useState, Fragment } from "react";
import AddContactForm from "./forms/AddContactForm";
import EditContactForm from "./forms/EditContactForm";
import ContactTable from "./tables/ContactTable";

const App = () => {

  const contactsData = [
    { id: 1, organization: "A Ltd.", name: "Carol", email: "[email protected]" },
    { id: 2, organization: "B Ltd.", name: "Paul", email: "[email protected]" },
    { id: 3, organization: "C Ltd.", name: "Emily", email: "[email protected]" }
  ];
  
  const initialFormState = { id: null, organization: "", name: "", email: "" };

  const [contacts, setContacts] = useState(contactsData);
  const [currentContact, setCurrentContact] = useState(initialFormState);
  const [editing, setEditing] = useState(false);

  const addContact = (contact) => {
    contact.id = contacts.length + 1;
    setContacts([...contacts, contact]);
  };

  const deleteContact = (id) => {
    setEditing(false);
    setContacts(contacts.filter((contact) => contact.id !== id));
  };

  const editRow = (contact) => {
    setEditing(true);
    setCurrentContact({
      id: contact.id,
      organization: contact.organization,
      name: contact.name,
      email: contact.email
    });
  };

  const updateContact = (id, updatedContact) => {
    setEditing(false);
    setContacts(
      contacts.map((contact) => (contact.id === id ? updatedContact : contact))
    );
  };

  return (
    <div className="container">
      <h1>Address Book</h1>
      <div className="flex-row">
        <div className="flex-large">
          {editing ? (
            <Fragment>
              <h2>Edit contact</h2>
              <EditContactForm
                editing={editing}
                setEditing={setEditing}
                currentContact={currentContact}
                updateContact={updateContact}
              />
            </Fragment>
          ) : (
            <Fragment>
              <h2>Add contact</h2>
              <AddContactForm addContact={addContact} />
            </Fragment>
          )}
        </div>
        <div className="flex-large">
          <h2>View contacts</h2>
          <ContactTable
            contacts={contacts}
            editRow={editRow}
            deleteContact={deleteContact}
          />
        </div>
      </div>
    </div>
  );
};

export default App;

index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

1 Answer 1

1

EDIT: As you're trying to download a file through the frontend, you're able to use your function pretty much anywhere. Just add for example a button, like this:

<button onClick={handleSaveToPC}>download</button>

and change your function to:

const handleSaveToPC = () => {
  const fileData = JSON.stringify(contactsData);
  const blob = new Blob([fileData], {type: "text/plain"});
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.download = 'filename.json';
  link.href = url;
  link.click();
}

Original answer:

I suppose you're using React for the frontend and node for the backend. If so, you could send the data to a backend route, and there write the data to the PC with this function.

I'd suggest using fs.

This is an example function for how you could do it.

const fs = require('fs')

const writeToJSON = (data) => {
  const DATA_PATH = '/path/to/file'
  fs.writeFile(
    DATA_PATH,
    JSON.stringify(data),
    (err) => {
      if (err) return console.error(err)
      console.log('Wrote data to ', DATA_PATH)
    },
  )
}

Sign up to request clarification or add additional context in comments.

2 Comments

Should I write above codes in App.js? Variable 'writeToJSON' is declared but not used. Where should I use it? Thank you.
No, fs only works in node. Have you set up axios or any post methods to send information to your backend?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.