Since it looks like you're doing touches, here is for the touch events (mobile). If you're thinking desktop, use mouseOver
instead. Some comments are in the code, but essentially you can keep track of all the changes locally and however you need to, send your data to the server to parse it and upload it to the file. This could end up being a very large file though so double check it isn't affecting performance too much once you're all set up! One alternative is to use the browser's native event instead to take the work off React.
Client
import React from 'react';
function Container({addTouch}) {
const updateCoordinates = e => {
e.stopPropagation();
e.persist(); // React synthetic events are pooled if not
// Can also use native event
// For more on events check out:
// https://reactjs.org/docs/events.html
const {clientX: x,clientY: y} = e.touches[0];
addTouch(e.timeStamp, {x: x | 0,y: y | 0}); // | 0 is Math.floor. Remove if you want exact px
// Using the timestamp as a key, but keep track of them however
}
return (
<div className="Container" onTouchMove={e=>updateCoordinates(e)}>
Container
</div>
)
}
function App() {
const touchList = new Map();
const addTouch = (timestamp, coordinates) => touchList.set(timestamp, coordinates);
const sendToServer = () => {
// You could put this on an interval to that
// sends the touch list and clears the map
const url = '//yourUrl/yourEndPoint/';
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify([...touchList]),
headers:{
'Content-Type': 'application/json',
// Include your credentials here depending on how your API is set up
}
}).then(res => res.json())
.then(response => console.log('Success:', response)) // or stringify response if getting back data
.catch(error => console.error('Error:', error));
}
return (
<div className="App">
<Container addTouch={addTouch}/>
<button onClick={sendToServer}>SEND TOUCH LIST</button>
</div>
);
}
Server
# Handle your parsing and saving on the server however
# This is basic python/django since not sure how your servers set up
# I remember the REST framework having some built in classes
# like a serializer to handle some of this stuff for you
# You can create your own model in models.py
# then just get the request data in views.py and use your model functions to handle
import csv
from django.http import HttpResponse # ,JsonResponse if you're sending the data back
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
@api_view(['POST', 'PUT'])
def post_endpoint(request):
"""
Save mouse coordinates to some file
"""
# Might want to try, except request first before doing this
if request.method == "POST":
data = JSONParser().parse(request)
filename = "touchList.csv"
with open(filename, "a", newline='') as file:
reader = csv.reader(file_obj, delimiter=',')
fieldnames = ['timestamp', 'x', 'y'] # if using models you can define fields=(...)
writer = csv.DictWriter(file, fieldnames=fieldnames)
for i in range(0, data.length): # or start at last file row
writer.writerow({
'timestamp': data[i]['timestamp'],
'x': data[i]['x'],
'y': data[i]['y']
})
return HttpResponse('Success', status=201) # 201: Created, or 200, etc.
# ...default response, error, etc.