How to pass app state in ReactJS to the backend? - javascript

I am working on a web app using ReactJS in which I have created a form and stored the values of all the input fields into state of the app. That is, the state of my App.js file contains values of all the input fields created in Form.js file. I want the information stored in state to be passed on to the backend so that I can process a dataset based on it.
How do I add a functionality so that on clicking a submit button everything that's in my app state gets passed on to the backend- say to a text file, or in a json file.
Basically I want to search through a dataset (using Elasticsearch) based on the information provided by a user in the form (using ReactJS).
I am new to React so I don't have much knowledge. I have made the web-app but I need suggestions on how to pass the information that I obtain through the form to a backend so that I can do further work.

How do I add a functionality so that on clicking a submit button
everything that's in my app state gets passed on to the backend- say
to a text file, or in a json file.
You can make a request for data to use in your application using Axios OR Fetch API. You can consume REST APIs using two of the most popular methods known as Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API).
The fetch() API is an inbuilt JavaScript method for getting resources from a server or an API endpoint. It’s similar to XMLHttpRequest
Axios is an easy to use promise-based HTTP client for the browser and node.js. Since Axios is promise-based, we can take advantage of async and await for more readable and asynchronous code. With Axios, we get the ability to intercept and cancel request, it also has a built-in feature that provides client-side protection against cross-site request forgery.
To know more you can refer this
Both these above methods, can be used to submit the data from your front end into the back end, so that the data is stored into the back end, and then you can perform several operations on it according to your requirement.
You can refer several blogs and documentation to know more about this:
Use axios to fetch data from an api in ReactJS
Fetch API for POST Request
Axios
Difference between Axios and Fetch API
Recently, I have also created an application, wherein I am integrating React with SpringBoot application.
In this Application. I have set up router and route, created and submit form, called GET, POST, PUT, DELETE request using axios (have also done with fetch API).
submitBook= event =>{
event.preventDefault();
const book = {
title: this.state.title,
author: this.state.author,
coverphotoURL: this.state.coverphotoURL,
isbnNumber: this.state.isbnNumber,
price: this.state.price,
language: this.state.language
};
const headers = new Headers();
headers.append("Content-Type", "application/json");
fetch("http://localhost:8080/rest/books",{
method:"POST",
body:JSON.stringify(book),
headers
})
.then(response => response.json())
.then((book) => {
if(book){
this.setState({"show":true, "method":"post"});
setTimeout(() => this.setState({"show":false}),3000);
}
else{
this.setState({"show":false});
}});
this.setState(this.initialState);
};
To view the full code, you can refer my Github Repository

You need to look into making XHR or using the fetch API (or axios) to make http requests to the backend API.

use axios for calling api urls that you have defined in the backend. you can watch a short tutorial on youtube to get familiar with the basics.

You may want to use Fetch API documented in MDN. It handles url request, including REST API to parse data over HTTP, e.g. JSON object etc.

Related

How to limit the axios get request results

I am trying use an axios request to fetch data from github api, but for some reason _limit is not returning the limited number of results?
await axios.get(`https://api.github.com/users/freeCodeCamp/repos?_limit=10`)
.then(
(res) => {
console.log(res.data);
}
)
The following http request is working perfectly by limiting the results
https://jsonplaceholder.typicode.com/todos?_limit=2
Whereas the following http request is not limiting the data
https://api.github.com/users/freeCodeCamp/repos?_limit=2
What's the difference between the above two requests?
The _limit parameter you see in https://jsonplaceholder.typicode.com is specific to their json-server software.
From the Github REST API documentation, you want to use the per_page parameter
const { data } = await axios.get("https://api.github.com/users/freeCodeCamp/repos", {
params: {
per_page: 10
}
})
My general advice for using any REST API... always read the documentation specific to the resource you're consuming.
Sorting options for API results are limited to created, updated, pushed and full_name (default). If you want to sort by something else, you'll need to do that client-side, eg
data.sort((a, b) => a.stargazers_count - b.stargazers_count);
For GitHub, the correct property is per_page.
Just bear in mind that limiting results has nothing to do with Axios or any front-end tool. It is a backend implementation, and any backend developer is free to do it the way they want. Although there are some standards, such as cursor pagination.
In a real project, the backend and frontend developer would have a "contract" for how this would work, so both know how the property will work.

Axios post request in React JS

Im on a React JS project and i need to request some data from a server.I want to obtain this information before the render , because i want to show the data on the browser the first time is charged.
This is the code i have written (Before the render() of a Component):
componentDidMount(){
axios.post('https://XXX',{
msisdn:"XXXX",
passwd:"XXXX"
}).then(res=>console.log(res.data))
}
But I obtain the following errors:
Errors obtained after the axios request
My questions are:
How can I solve this problems without modifying the CORS conf on the server?.
I have my react project on a server and i was thinking about if it would be possible to make the request from the server and then send the data or obtaine it from React.
Thanks in advance!

why to use indexeddb instead of cache api for dynamic content

I am using service worker and precache assets in install event.
I also have fetch listener which intercepts requests and caches then at runtime dynamically. I know that people say to use indexeddb for dynamic content such as json data and possibly images.
Question: Why isn't it a good practice to use cache API for that json data too even though it's request/response storage?
The reason I am asking this is because I tried the following: I have index.html and main.js as precached in install event and in main.js I have axios request which returns some json and puts it in index.html. If I use dynamic caching which means when the request to that json api endpoint gets made, it goes first to my service worker, which gets the response and puts it into cache. Then I tested that and when refreshed the page in offline mode, I still got the same result (json data put in index.html accordingly).
So I guess even though Cache API store request/response, it still worked for json endpoint api urls flawlessly.
Any good idea why to prefer indexeddb over cache API while using service worker?
It's perfectly fine to cache JSON data using the Cache Storage API, as an alternative to using IndexedDB. I would expect similar performance characteristics, and in both cases you could read/write the data from either the service worker or window context.
It would be slightly more awkward to use the Cache Storage API if you have JSON data that isn't already associated with a Response object, or that doesn't have a "real" request URL, since you'll have to effectively "fake" them. But that's not particularly hard to do:
const data = {
// some data
};
const jsonString = JSON.stringify(data);
const jsonResponse = new Response(jsonString, {
headers: {
'content-type': 'application/json',
},
});
const cache = await caches.open('json-cache');
await cache.put('/some-json-url', jsonResponse);

ReactJS - Handle POST requests using react router dom

Is there a way to handle POST requests using the react-router-dom (npm) library?
Why? The payment gateway will redirect the user, who successfully payed, back to the platform. I can use a GET or POST request to transfer data with the redirection page. But I don't like having the data visible in the URL. Other options are always welcome, I'm using a REST API (Node.JS, Express) and a website/dashboard (ReactJS)
I get what you're after but you can't POST to the browser. If you're uncomfortable passing data as GET params in a URL, you could:
store data in LocalStorage when user submits
deliver server-rendered, static HTML upon redirect that contains purchase information
asynchronously get user's purchase data upon page load with AJAX or fetch() (or your favorite data-grabbing util).
Since you're in a React world, I'd recommend the third option here. How to fetch data, build an API endpoint, store data, then display it goes well beyond the scope of this question so I'd suggest some Googling. Here's a starting point: https://code.tutsplus.com/tutorials/introduction-to-api-calls-with-react-and-axios--cms-21027
You can handle the POST request on your express server then redirect to a static page of your app :
app.post('/payment_webhook', (req, res) => {
const paymentOk = req.body.payment // handle POST data
if (paymentOk) {
res.redirect('http://app.com/payment_success');
} else {
res.redirect('http://app.com/payment_failed');
}
});
I was discussing the same with a friend and so far we saw 2 ways of doing this:
let the payment gateway return_url be an endpoint of the backend API (rails api), which will do the commit to the payment gateway (and probably updating the order in the BD), and then it will do a redirect back to your frontend app
store the gateway trasaction token on the order object in the DB, and let the payment gateway return_url to return to a dynamic order url, therefore, react will now which order should render, then asynchronously ask the backend (rails service) to extract the token from the order object and do the commit (confirmation) and update it's status and return the order object back to react, then react can now show if the order was successful or not.
we opted for option #2, since I feel that the frontend (react) shall be the main communication gateway to our system, and the only one communicating to the backend shall be the frontend.
UPDATE: option #2 did not work since you cant do POST to a react-app therefore, we make the return_url to be dynamic, and we immediately redirect to the frontend with a url with the order_id as query param, then, the frontend when tries to load the order, in the backend we do the payment gatway confirmation, update the order object and return the updated order object to the frontend

Nextjs global api calls

I am developing react based web application using NEXT.js,. As specified in NEXT.js, documentation to fetch the data before page loads, i am putting required action dispatch code in getInitialProps of the specific page. but some data fetching calls(action dispatch) like fetching authenticated user's data will be common to all the pages, so is there any way to dispatch such actions from single place before page load.
Thanks!
update, now you can use getServerSideProps and nextjs provides an easy way to get user cookie : How to use cookie inside `getServerSideProps` method in Next.js?
--------- old answer ---------
simple answer: use cookie, code refer https://github.com/nextjs-boilerplate/next.js-boilerplate https://github.com/nextjs-boilerplate/next-fetch
-- details --
I had the same question when I first adopt next.js, as it worked in react, people prefer use a token to tag authed user and fetch always run in front-end. But as next.js made ssr a build in feature, I tried and find auth by cookie is possible, and I start https://github.com/nextjs-boilerplate/next.js-boilerplate and split out a fetch based on cookie https://github.com/nextjs-boilerplate/next-fetch
-- how it works --
1.client side fetch: use fetch option option.credentials = 'include' and option.headers.Cookie=document.cookie will patch cookie into your request. Bnd when fetch back result, this become wired, you cannot access cookie header, so you have to use another header and additional logic needed in backend logic like res.header('custom-set-cookie', res.getHeader('set-cookie'))
2.server side fetch: first you need the express request object, and get cookie like req.headers.cookie, then pack it into fetch request option. when fetch back, get cookie like r.headers._headers[cookieHeaderName] and pack into response res.header('set-cookie', setCookie)
then after you pack this transfer up, you can simply call a json api and cookie will automatically transfered. And if you don't need to change cookie through header (you can through js), you can ommit the extra handle like res.header('custom-set-cookie', res.getHeader('set-cookie')) in api
you can try my ssr login here http://nextjs.i18ntech.com/login

Categories