I am working on a graph visualization using cytoscape.js in my reactjs app. What I am trying to do is to add the ability for a user to save and render graphs linked to their profile. I am authenticating my react app using @auth0/auth0-react. And I am exporting my graphs to JSON by downloading the graphs as a JSON file and later import the graphs back to my app. Exporting the graphs to a JSON file and uploading the same JSON file back the app works fine but, I would like to implement a saving to memory/DB (postresdb) functionality and the saved graph should be tied to the current user. The only code I have is for downloading to JSON file and uploading back to the app. Any help with code snippets will be highly appreciated.
Code for downloading the graphs:
const exportJson = () => {
// GET GRAPHS AND ELEMENTS
const jsonGraph = graph.json();
const { elements } = jsonGraph;
// ATTACH STYLES
if ('nodes' in elements) {
elements.nodes.forEach((node, index) => {
const sNode = graph.$(`#${node.data.id}`);
elements.nodes[index].style = sNode.style();
});
}
if ('edges' in elements) {
elements.edges.forEach((edge, index) => {
const sEdge = graph.$(`#${edge.data.id}`);
elements.edges[index].style = sEdge.style();
});
}
// DOWNLOAD JSON FILE
const data = { graph: graph.json(), styleGraph: jsonGraph };
const dataStr = `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(data))}`;
const downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute('href', dataStr);
downloadAnchorNode.setAttribute('download', `cag.json`);
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
};
And code for uploading the graphs:
const uploadJson = (contents) => {
let json;
try {
json = JSON.parse(contents);
} catch (e) {
return setError('Json file is not properly formatted.');
}
graph.json(json.graph);
// APPLY STYLES
const { elements } = json.styleGraph;
if ('nodes' in elements) {
elements.nodes.forEach((node) => {
const sNode = graph.$(`#${node.data.id}`);
sNode.style(node.style);
});
}
if ('edges' in elements) {
elements.edges.forEach((edge) => {
const sEdge = graph.$(`#${edge.data.id}`);
sEdge.style(edge.style);
});
}
return resetAppValues();
};
In summary, this is what I would love to achieve for now:
- Prevent my graphs from getting lost when I refresh the browser or logout of the app. I want them to persist.