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"));