Fetching remote data multiple times based on user choice within a page - javascript

I am using next js for developing a web app. I have following page:
<page>
<component_1>
Fetch the data from remote server using `getInitialProps` (I could use `getStaticProps` or `getServerSideProps` too)
Show the data to user and get the user input, pass on to component_2
</component_1>
<component_2>
Based on the user selection, fetch remote data and show it in the page
</component_2>
</page>
During user interaction, either component_1 or component_2 is visible.
getInitialProps is allowed to be used only on page level components (URL loading) and not called in sub-components (this way, I am not able to get remote data from component_2). Should I have to handle this scenario by using different URLs? Or is there a better way of handling in the same page?
Thanks for the help in advance!!!

getStaticProps, getInitialProps and getServerSideProps are functions that fetch data for pre-rendered pages and components.
Your component needs to fetch data based on the user actions, so you need to fetch data only on the client side. You can fetch data on the client side in any React component.
Example using SWR hook. However, you can use any preferable method to fetch data.
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetch)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
Suggested reading: Next.js fetching data on the client side

Related

use global cms data in next app without getInitialProps

I'm using a Headless CMS based in another country that is not near my own, and each request to this CMS takes at least 1.5s to return a payload (which can be a ridiculously long time to wait when you're making multiple requests).
Now, I can use getStaticProps for each page requiring CMS content. But, since I have global components that need information from the CMS too (such as the navigation and footer), this destroys Next's ability to render each page statically, and it forces me to use getInitialProps in _app.js.
Now, before you say:
Just create a request to the CMS on every page using getStaticProps.
That will remove the ability for my website to be a proper single-page application and cause a re-render for elements in the layout that don't need to be re-mounted while navigating. This ability to navigate without re-mounting is vital since the navigation has functionality that relies on it.
Here is an example of what my _App.getInitialProps looks like:
const appProps = await App.getInitialProps(context);
try{
// Retrieve data from CMS.
// Yes. I do have to create two requests to the CMS to retrieve a full payload,
// as that is how their API is setup, unfortunately.
const dataOne = await fetch(...);
const dataTwo = await fetch(...);
// Yes, I'm aware this isn't actually how it would work.
return { ...dataOne, ...dataTwo, ...appProps };
} catch(error){
console.log("Error in _App component:", error);
}
return appProps;
The ideal workaround for this would be to use getStaticProps in each component that requires it - but this isn't a feature that Next offers, unfortunately.

Best way to dispatch an action client-side upon Sign In using Redux, React, NextAuth

I am writing a web app based on the Spotify API. Once the user logs in using NextAuth, I want the app to automatically load the user's playlists.
I currently have it set up so that there is a button to load playlists and the button does not appear unless the user is logged in - this works and is simple. However, the button is unnecessary. There is no use-case for the app that doesn't begin with loading the user's playlists.
I currently have a thunk action written which was dispatched by the "Load Playlists" button to fetch the playlists asynchronously and add the playlists to the redux state.
I can think of multiple possible options to get the automatic loading to work well, but I imagine there has to be a clean way. NextAuth has the [signIn event callback]https://next-auth.js.org/configuration/events#signin which seems like the right place to start. But since this would be run server-side, it would need some way to contact the client.
Just observe the status in. a useEffect and once the status is authenticated call the load playlist action.
import { useSession } from "next-auth/react"
export default function Component() {
const { data: session, status } = useSession()
useEffect(() => {
if (status === "authenticated") {
Load_Playlists()
}
}, [status])
return <Main>
}
what I usually do is save the Jwt on local storage then use a use effect to get it if not existing then get it from the server using the thunk action.
also, see How to wait for action to complete before redirecting in react redux? how to define the thunk

How to pass app state in ReactJS to the backend?

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.

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!

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

Categories