I have a JSON file 'DealerList.json' and I can access it from my app by importing it using
import DealerList from './json/DealerList'
let tasks = DealerList;
The tasks here contain the JSON and I can easily access it.
Is there any way by which I can update the JSON back like if I update the values OR if I delete the values. I have also tried require("fs") but that too is throwing error.
The JSON file is present in a folder called json in the React App.
No, and this is a good thing. You do not want any web browser to be able to come along and rewrite files on your HTTP server.
Write a web service which will read and update the data based on HTTP requests (with appropriate authentication/authorization to stop undesirables from changing the data). Then interact with it via XMLHttpRequest / fetch / an abstraction library wrapping one of them (like axios).
(Or use localStorage if you want to store the data on a per-browser basis rather than shared between visitors).
Related
My React Native project has a static JSON file from which I access some properties and I am wondering if it is possible to overwrite that JSON during runtime.
Let's say I have a button that makes a GET request for an updated version of that JSON, would it be possible to overwrite that JSON file with the result of my GET request?
I imagine I'd need some sort of React Native filesystem dependency.
you can use a state where you put your JSON data, which get updated every time you make a GET request, which is gonna overite the previous state(data)
Edit : you can use a caching system with RFNS, we have done that in our app and it works perfectly, you just need to know how to use react-native-fs package.
Yes, head over to RNFS documentation
If I use a json file stored in one of my GitHub repos as a mock backend, I know how to fetch and read all the data. Is it also possible to edit or post new data to this json file? Would an alternative mock backend like Mocky.io be a better solution (to achieve full CRUD)?
I think you could store the information inside csv files or somehting like that, you would be recreating a database engine as MongoDB & create your own reader to find the info, or you could store the users info using local Storage,
However this would make your app very limited.
Here's the link for the documentation of local storage
https://developer.mozilla.org/es/docs/Web/API/Window/localStorage
Well if you want to try out CRUD operations you can use free JSON APIs like http://jsonplaceholder.typicode.com/ or
https://mockfirst.com/
where you can create, read, update and delete data using various api end points. It is better to go this way first then you could move on to updating a JSON file.
(UPDATE)
You can use https://jsonbin.io/
Here you can place your own data and use it as an API.
I am writing my first web application with Javascript and WebGL. For now I am running the app on localhost from Apache. The app needs to work with data that is provided instantly. Until now I worked with AJAX calls that happen during runtime which doesn't work out for my purposes anymore. So instead of serving individual files from Server to Client when asked, I want the application to load all files from the Server to Client side at initialization time (I want this to happen automatically at the start so I don't have to add every new file as a url in the html index). I understand I should do this with Server Side scripting; probably with PHP since I have a Apache localhost? I have different folders which hold my necessary resources in a uniform dataformat (.txt, .png and .json). So what I want to do is, before the Javascript app starts, look through the folder and send one object per folder that holds filenames as keys bound to filedata. Is my intuition right that I need to do that with PHP? If yes, where do I start to tell my application what to do when (first start serving files with php, then start the javascript app)? How do I do this on localhost? Should I already think about extending my toolset (e.g. using nodeJS on ServerSide(locally for now))? If so what lightweight tools do you propose for this kind of work? I feel I am missing some design principles here.
EDIT:
Keep in mind that I don't want to specifically call a single file... I am already doing that. What I need is a script that automatically serves all the files of a certain folder on the server to the client side at init time of the app before the program logic of the actual application starts.
Your question is kind of broad so I'll try my best. Why does AJAX not work for real-time data but loading all the files once does? If you're working with real time data, why not look into a websocket or at the bare minimum, AJAX queries?
If you want to pass data from the server to the client, you will need to use a HTTP request no matter what. A GET request or POST request is necessary for the client to request data from the server and receive it as a response.
You could theoretically just pass the data from PHP straight to the view of the application (which is technically done through a GET request whenever a user requests data such as .php files from the server) but this isn't as flexible as if Javascript had access to the data. You can do some hacks and 'transfer' the data from the view to Javascript with some .value methods, but this isn't ideal and can be prone to some security holes. This also means data is only being passed once.
So what would need to happen is that the data would need to be processed upon initialization and then immediately transferred to the client by use of Javascript and HTTP requests.
So if you want Javascript to have access to the data and use it in variables or manipulate it further, then you'd need to use an HTTP request such as GET or POST which is called by Javascript. Otherwise, you need to immediately pass the data to the view upon initialization (through PHP), but this means you can't work with real-time data because the data is only being passed once when there is a page refresh.
Example of scandir():
<?php
//scandir() returns filenames, not data from files
$fileArray = scandir('datafolder/') //this is a relative path reference to the folder 'datafolder'
$finalArray = [];
foreach($fileArray as $filename){
tempArray = [];
$file = fopen('datafolder/' . $filename, 'r'); //im pretty sure scandir only retrieves the filenames and not the path, so you might need to append the filepath so your script knows where to look
$tempArray = fgetcsv($file, 1024); //temp array to hold contents of each iteration of foreach loop
array_push($finalArray, $tempArray); //this will store the data for later use
}
Or the data can be used however, depending on what it is. Say, if you need to combine the data from multiple .csv files, you can read each file and append it to a single array. If you want to read multiple distinct files and preserve the independence of each file, you can create multiple arrays and then pass back a single JSON encoded object that contains each file's data as a separate attribute of the object such as:
{
'dataOne': [0,1,2,3,4,5,6...],
'dataTwo': ['new', 'burger', 'milkshake'],
'dataThree': ['Mary', 'Joe', 'Pam', 'Eric']
}
Which can be created with a PHP associative array using one of the following methods:
//assuming $arrayOne is already assigned from reading a file and storing its contents within $arrayOne
$data['dataOne'] = $arrayOne;
// or
array_push($data['dataTwo'], $arrayTwo);
// or
array_push($data, [
'dataThree' => ['Mary', 'Joe', 'Pam', 'Eric']
]);
Then $data can simply be passed back which is a single array containing all the different sets of data, if each set needs to be distinct.
I have a fairly large Application and I'm currently trying to find a way around having to pass Data from PHP (User Tokens for 3rd Party API's and such) through the DOM. Currently I use data-* attributes on a single element and parse the Data from that, but it's pretty messy.
I've considered just making the contents of the element encoded JSON with all the config in, which would greatly improve the structure and effectiveness, but at the same time storing sensitive information in the DOM isn't ideal or secure whatsoever.
Getting the data via AJAX is also not so feasible, as the Application requires this information all the time, on any page - so running an AJAX request on every page load before allowing user input or control will be a pain for users and add load to my server.
Something I've considered is having an initial request for information, storing it in the Cache/localStorage along with a checksum of the data, and include the checksum for the up-to-date data in the DOM. So on every page load it'll compare the checksums and if they are different (JavaScript has out-of-date data stored in Cache/localStorage), it'll send another request.
I'd rather not have to go down this route, and I'd like to know if there are any better methods that you can think of. I can't find any alternative methods in other questions/Google, so any help is appreciated.
You could also create a php file and put the header as type javascript. Request this file as a normal javascript file. <script src="config.js.php"></script> (considering the filename is config.js.php) You can structure your javascript code and simply assign values dynamically.
For security, especially if login is required, this file can only be returned once the user is logged in or something. Otherwise you simply return a blank file.
You could also just emit the json you need in your template and assign it to a javascript global.
This would be especially easy if you were using a templating system that supports inheritance like twig. You could then do something like this in the base template for your application:
<script>
MyApp = {};
MyApp.cfg = {{cfg | tojson | safe}};
</script>
where cfg is a php dictionary in the templating context. Those filters aren't twig specific, but there to give you an idea.
It wouldn't be safe if you were storing sensitive information, but it would be easier than storing the info in local storage,
My web application uses file which has been updated by other process. My application reads the content of the file using ajax
xmlhttp.open("GET","/config/myfile",false);
xmlhttp.send();
Once response is received then app parses this response and shows that values on Web UI. The file contains 50 fields and whenever I want to read any single field I need to open whole file.
Is there any way to get the values of single field based on key instead of reading whole file.
As per my understanding we need to read and open file and then parse the response text. But would like to know is there any way to reduce the file calls with any other method.
I want to achieve this to reduce the file I/O operations. Since other processes are writing in to it and at same time my web app accessing to read the latest value.
Any other option would be appreciated.
Note :- I do not have to use any server side scripting lang option.
Regds