React.js: Best practices for API's grouping - reactjs

I have been using Angular for 3 years. I have created some small and big projects. In every project, I have used proper folder structure for API calls(which many resources suggest). Below is a simple example
constants.ts
export const uploadData = `${url}/uploadData`;
service.ts
uploadData(formData: FormData): Observable<any> {
return this.http.post<any>(constants.uploadData, formData);
}
And in the component file, I import the service and call the API like this
this.service.uploadData(formData).pipe(take(1)).subscribe((res) => {
// do something
});
I specify all my related APIs and services in respective folders and call them wherever I need them. It's been 5 months since I started learning React and ReactNative. Now I am comfortable with both I started doing a major project. Now, the resources I followed to learn React didn't follow the proper structure(Create the API in whichever folder is required and call it with fetch/axios). Found some resources that follow structure but not effectively like how I did it in Angular. I can't find any resources with the requirement. It would be helpful if I can get one example of how we can have the folder structure like in Angular so that I will follow the good approach, instead of ending up writing bad code. (I am using Axios)

Related

Get a list of files in a react web application

I have a directory full of text files that I need to read in my react web app
-resources
|-file1.txt
|-file2.txt
|-file3.txt
I would like to store this resources directory somewhere in the app such that the contents of resources can be listed, and individual files can be iterated over on a line-by-line basis.
currently, I'm stuck on listing the files. I'm storing them like this
-node_modules
-public
|-resources
||-file1.txt
||-...
-src
But I really don't care where the resources directory is located. I tried using list-react-files based on this, but got Module not found: Error: Can't resolve 'fs'.
for further context, I was thinking the code to scan for files would be in in App.js, such that the scanned files could be used to populate certain components.
import React from "react"
import './App.css';
...
function App() {
//searching for files
var files = [...];
return(
//create components which can list and work with the files
...
);
}
export default App;
So, to summarize the question, how can I list files in reactJS?
p.s.:
this project was made with create-react-app
part of the point is that it should be easy to add new files to this directory, but I see no reason this process has to be "dynamic"
When people are using your react page, it is "running" on their computer and the software does not have access to all the files and data you'd like to use.
You will need to do this at "build time" when your service is being packaged up, or "on the server".
When you are building your react app, you can hook into processes that can find files and perform operations on them. Gatsby might be your best bet. Look at how people add "markup" files to their projects, built a menu from them and then render them as blog articles. NextJS, Vite, and other frameworks and tools will work, you may just need to learn a bit more.
The other approach, to do this "on the server" means when you are running code on the server you can do almost anything you like. So, your react app would make a call (e.g. rest request) to the server (e.g. NodeJS), and the code running on the server can use fs and other APIs to accomplish what you'd like.
From what you describe, doing this as part of your build step is probably the best route. A much easier route is to move this data into a JSON file and/or a database and not crawl the file system.
Looks like its a client side rendering app and not server side (node app). Resources folder you trying to list is residing in server and react app (javascript) running on browser can't access it directly.
To whom it may concern, I spent more time than I should have working on this. I highly recommend converting everything to JSON files and importing them. If you want to be able to scan for JSON files, make a JSON file that includes the names of all your files, then import that and use that for scanning. Doing things dynamically is a bare.
If you don't reformat, you'll likely need to use Fetch, which is asynchronous, which opens up a whole can of worms if you're using a framework like React.
If you're just importing json files, it's super easy:
import files from './resources/index.json';
where index.json looks like
{
"files":[
"file1.json",
"file2.json"
]
}
if you need to import the files more dynamically (not at the very beginning) you can use this:
var data = require('./resources/'+filename)
this will allow you to scan through your files using the index.json file, and load them dynamically as needed.

Microfrontends React/Component based splitting

Background:
I am confronted with the task to modernize a tool and convert it to microservices with a react frontend. My idea was to have a general top-level component containing e.g. the Nav and a component for each microservice that contains the functionality.
Approaches:
bundle the components locally so that it becomes effectively a monolithic frontend and the the forntend code is seperated just in the repo.
I think that would give up on the advantage of not having to redeploy your entire app for every change
lazy-load a minified bundle of each of the components from the microservice by defining them in a config file
With this approach I could just webpack each component on their own and async import it from the Main Page but maybe there would be a huge overhead
I read about component based splitting with react-loadable and bundling react-router or webpack, but I can't find information on how to load small bundles form different URL-Endpoints.
Question:
Is it possible to bundle react components on their own and import them from different Resource-URL's and how would one approach that ?(Or is React even suitable for that)
So after quite some search and experiments I found the Project Mosaic of Zalando, which is what I wanted. It offers a great way of React Component Splitting to support Micro Frontends. Note however that it is probably not suitable for smaller projects as it takes some time to get into the material and setting up all necessary applications.
Take a look at the below link:
https://www.martinfowler.com/articles/micro-frontends.html
I've recently made a project based on that article and I think that it might be what You are looking for.
I made the wrapper app which is rendering the microfrontends dynamically on the runtime based on the URL and routings. In the article above, there is a demo app showing the idea.
Every microfrontend is the separate project with it's own code repo.
https://demo.microfrontends.com/
Each app is hosted and js chunks are getting loaded on the runtime. This code might make it a little bit more clear what's going on there.
componentDidMount() {
const { name, host } = this.props;
const scriptId =micro-frontend-script-${name}`;
if (document.getElementById(scriptId)) {
this.renderMicroFrontend();
return;
}
fetch(`${host}/asset-manifest.json`)
.then(res => res.json())
.then(manifest => {
const script = document.createElement('script');
script.id = scriptId;
script.src = `${host}${manifest['main.js']}`;
script.onload = this.renderMicroFrontend;
document.head.appendChild(script);
});
}`
I hope You'll find that helpful :)
Good luck!

Creating a webpage with a unique URL using react/firebase?

I'm pretty new to react and building out a little prototype using Firebase as a backend. One of the primary functionalities involves a user writing a post in an editor, which is saved to firebase. On submit in the editor, I am trying to create a new standalone page for the post with the firebase uid as the ending part of the new unique URL.
The problem I'm having is figuring out a way to create the new page on submit. I haven't been able to find any documentation for a similar problem like this specific to react or firebase, and was just wondering on a high-level what a good approach to executing this might be? Thanks
The newly launched Firebase Hosting + Cloud Functions integration can help here. The first bullet point in the documentation looks like it describes your use case exactly.
You also mentioned React. There is a handy sample project showing how to implement an isomorphic React app with Firebase.

Splitting React App to 2 Independent Parts

The app I'm developing (Node.js + Express + React + Alt) is addressed to 2 types of crowds - Teachers, for which it is a large app with multiple routes, and students, for which it is a very small app with a single route.
I want to separate these 2 parts completely, so the code of teachers part won't be loaded when students route is rendered.
I have two reasons in mind:
Better loading times for students' app - There's no point in downloading and running that big chunk of JavaScript when I know it won't be needed.
Security Aspect - Although there's no data exposure, I'd still rather hide the code the teachers use from the students.
Is there an easy way to do this?
Can I use one React app (And one React-Router)?
Thanks for any help!
The best way to implement this is using the Webpack feature Code Spliting. This allow you automatically split your code in chunks and only load the require code when is needed.
You can see the React Router example: huge-apps
The magic happen in the internal components (require('./routes/*')), here they use the callback method to get the components and look something like this:
export default {
path: 'nameOfComponent',
getComponent(location, cb) {
require.ensure([], (require) => {
cb(null, require('./components/nameOfComponent'))
})
}
}
Require.ensure is detected by Webpack and generate a new chunk with all the code and his internal dependencies.
When the application is executed in the browser the first load only get the main chunk with the routes definition, and each router components is loaded on demand (when you change of route).
For me, this is the most clean way to do it. Because you delegate the responsibility to the build system. In Webpack 2, you could use System.import instead of require.ensure, and is a more ES6 standard.

Structuring a NodeJS app using Angular and NodeJS Tools for Visual Studio

I would like to know how do you usually organize your application structure when building a NodeJS application using nvst. When I create my app it automatically build up this structure for me:
So, the first thing that came to my mind was, where should I put my controllers and how do I connect them with the routes and views?
Also, how can I organize my unit testing logic?
An NTVS angular app is still just an angular app. The advice in AngularJS application file structure applies.
Going further, General principle: You should be able to find what you're looking for without excessive drilling or scrolling.
Schemes:
for smaller apps, folder by type: controller; service; model
for larger apps, folder by function: user; cart; search; grid
I lean toward folder by function, as it keeps files that may need to be modified at the same time together.
As for unit tests, I have seen either myfile.test.js or myfile.spec.js sitting right beside myfile.js. If you do not include the test files in the index.js, then they won't be loaded and don't cause a problem.

Resources