Initializing component with parameter set from other page in nextjs - reactjs

I have 2 components on separate pages in nextjs. The way I would like my app to work is:
User inputs some data on page A and clicks submit
A request to my backend is sent and it returns a 'accessToken', at the same time the user is redirected to page B
To load page B the 'accessToken' is sent to an external service to initialize the component provided by that service
If the user leaves the page and returns, the 'accessToken' should be still set and they should not need to re-do step 1,2 but if they request a new one then that should also be updated in page B
Below the component provided by the external service for reference:
<WebSdk
accessToken={token}
expirationHandler={handler}
config={config}
options={options}
onMessage={messageHandler}
onError={errorHandler}
/>
How should I store and read the access token? Do I need to use useState or useEffect? Do I need to set a cookie or localStorage?

Neither useState nor useEffect is good choice for this condition.
You can use both cookies(low security) and localStorage , but I recommend using sessionStorage(it has expire time) .I

Related

How to not lose my information in props when i reaload my pages?

I'm new in react and i'm studing a method to make connections with Firebase to my Project.
With props I can pass an ID and search it in firebase, but when i reload my page, all the props are lost and i have this message in the image:
The value is Undefined because the props are losing their values
Is there any other way for this information don't lost?
I dont try anything because idk what to do.
The ID in the props will be used in useEffect() on my page.
Edit:
There is the Cards Image:
Cards
And here it's when i click on the card "Pinscher":
The page when i click on Pinscher
But when i Reload the page "Pinscher", i lost the Id passed with props.
The most straightforward way I know to persist data over a reload is to save it to localstorage or sessionstorage. Which one to use--and whether it's appropriate--depend on your actual use case, which we can't comment on without more knowledge of your project.
Assuming you did want to use that, a basic implementation would be to write helper functions when you set state to also save the data to storage. Your initial state load would then look for storage information as its default and then fallback to null if it can't find anything in storage.
const [arbData, setArbData] = useState(window.localStorage.getItem('arbData'));
const setArbDataWrapper = (data) => {
setArbData(data);
window.localStorage.set('arbData', data);
}

Is it normal in React to use `useState` to manage whether a form has been submitted?

A basic online React tutorial is demonstrating how to create a React-based form with 3 fields (first name, last name, and email). Surprisingly to me, it has useState to manage whether or not a form has been submitted, which it uses to decide on whether to show a success message or not.
Please note that it does NOT make an actual form submission (i.e. no API calls) and so I am wondering whether it is using state only for simulation purposes here.
Here is a snippet:
const [submitted, setSubmitted] = useState(false);
...
{submitted && !values.lastName && <span id='last-name-error'>Please enter a last name</span>}
...
{showSuccess && <div class='success-message'>Success! Thank you for registering</div>}
...
Is it normal for real-world React applications to useState to manage whether or not a simple form such as 'contact us' or 'feedback', etc, has been submitted? My guess is that normally there would be no need to do so.
As the resulting API call, whether 'success' or 'fail' could simply be used to show the state of the error message. Thereafter, the form should ideally reset itself to allow for another submission. So, there would be no need to store the state of the submitted form. Am I correct in my understanding?
Your question is a little confusing. basically if you want to store a data in React and this data has direct effect on your application you mostly should save it in state. When you submit a form, the form onSubmit event handler will be called and you can do everything in that event handler. It's clear that in the tutorial submitted state is a flag to simulate the fetch process. Usually when you want to handle submitting a form and fetching API you should store 2 items in state:
Error and Loading
You should use loading flag to show a loading indicator during fetching API and use error to check if any error exist store and show it. If API fetches successfully you may redirect user to another page, show a notification or change some data in your state. It's up to you. But be sure the submitted state in your tutorial is just an example ans simulation. But it has real usages in real world! Hope it helps!
Here is an example: I want to add a user by fetching an api and i want if api fetches successfully add it to the list:
Sandbox

angular 4 execute function when user leave

I do some functions when user load a component and create data I create function clear and delete what I did but need load this function when user refresh or change a route or close the page I'm used HashLocationStrategy on routes !

Firebase and React - check user auth status

I'm working on app based react+mobx and as backend use the firebase.
Currently on the app start i need to check if user is logged in.
I'm doing it with firebase.auth().onAuthStateChange listener, but because it's async function - the first response always null.
So my current solution is display some loading message and put setInterval function with status checking in componentWillMount lifehook.
The question is - is there any more elegant solution to this issue?
Before you call firebase.auth().onAuthStateChange, modify your state to be something like: state.authenticatedUser: 'pending'. Have your observer change that state to real user info once it is called.
Have your components take into account state.authenticatedUser when rendering and render either "authentication pending" or "authenticate user"

Server-side rendering for a specific selection

Let's say my app is a list of many items. There's a lot of items so I don't want to include all the items in the redux state.
When a user visits me at myapp.com/item/:itemId, I want to display the selected item. Currently I make an api call in componentDidMount to fetch the item and store the response in myReduxState.selectedItem. However, this shows the user and unfinished page until the api call finishes.
Is there any way I can get around this?
The pattern I tend to follow is to have a state of fetching being tracked in the redux state. Once the api resolves you just make sure the state is set correctly and then in your render methods use that to determine what you are rendering.
render() {
if (this.state.fetching) {
return <div> // put whatever you want here, maybe a loading component?</div>
}
return (
// put the regular content you would put for when the api call finishes and have the data you need
)
}
I solved this problem by making the creating the state on the server side. I get the itemId from the url in my express route and get the details of the specific item. I use this to create the state and pass it to the front-end.

Resources