How to wait for information (currentUser) before componentDidMount - reactjs

I have a user profile page, when I refresh the page my redux store clears and then I have a fetch all the information again from the backend... but my profile page begins to mount before I get that information back.
I this function in my "loggedInRoutes.js". It will get the currentUser from the JWT token I have in localStorage, and save the userName and ID, etc, in my Redux Store
componentDidMount(){
if (localStorage.length===0){
this.props.history.push('/')
}else{
this.props.dispatchCurrentUser()
}
}
It's in the top level of my routes, the switch statement with my route rendering is in the same page.
In my profile page. (I need to check if the currentUser is friends with the user who's profile I went to, that's why I need both infos from the start).
componentDidMount(){
this.props.fetchProfile(this.props.currentUser, this.props.match.params.userId)
this.requestFriendshipFunction()
}
This works if I already have the currentUser in my redux store, but if I do a page refresh while on the profile page, the componentDidMount in the profile page gets called before I have that information, even though I'm calling the "dispatchCurrentUser" in a more container/parent component "loggedInRoutes".
Saving the currentUser info in local storage seems like a bad idea, and I'm not sure where to go from here.
Thank you.

Related

Passing Access Token from an api to different pages

So I'm currently using the Spotify API with reactJS and get the access token of a user when the login is authenticated by Spotify, it redirects to the first page that I set it to, ('/') of Component={Home}. But from that Home page, I want to route to a different page with the path '/playlist' onClick of a button in which I push the url by,
this.props.history.push('/playlist/#access_tokens=' + spotifyApi.getAccessTokens())
This is the only way I got it to be with the access token passing in the URL.
Is this bad practice?
it's hard to understand your goals for me, but if you want to pass access_token only by url, you can use state to hide token from the user
this.props.history.push({
pathname: '/playlist',
state: {
accessTokens: spotifyApi.getAccessTokens()
}
})
and then get it by the next way
const location = useLocation();
const tokens = location.state && location.state.accessTokens;
But i can't understand why do not you pass your token to any management library like redux, mobx or some other browser storage (localStorage, sessionStorage)?

Reactjs router - this.props.history.push is not rendering URL queries from same path

I have a component that uses history.push to navigate URLs. The problem is that one of the URL paths relies on search parameters in the URL to render parts of the component. It works fine when the user initially navigates to the url, but when they update it while inside that path it doesn't work. Heres's an example:
App.js
<Router>
<Route path="/jobs" component={Jobs} />
</Router>
The url for jobs will contain a job ID, which is used to retrieve the data from the backend - ex: /jobs?id=6583ghawo90. With that id I make a get request inside componentDidMount() of the Jobs component to populate the page. Inside the Jobs component a user can navigate to a new job, which updates the url through this.props.history.push(`/jobs?id=${newjob.id}`). The problem is, when the user navigates to the updated URL, the component doesn't call componentDidMount() therefore doesn't request the new data. I can fix this by manually calling this.componentDidMount(), but this doesn't work if the user hits the back button in their browser.
Is there anything I can do to fix this issue?
You shouldn't be using componentDidMount but componentDidUpdate:
componentDidUpdate(prevProps) {
// compare previous jobId and current jobId
// refetch data if needed
}
I would suggest you use hooks if you are in the beginning of the development process.

Better way to update react component on event

I'm making a web-app in which I use React, together with Firebase Authentication. I have a login page and I want it to redirect to a different page when a user is already signed in.
To check if the user is logged in I use a method to retrieve the User object, it returns null when a user is not signed in and a user object with all sorts of data if they are.
I have an if statement in my render method (of the login page) which checks if the user is logged in, but I ran into an issue. When a user first loads up the page it takes around half a second for the Firebase API to retrieve the user object and until that is completed my user object will return null.
This makes for an issue where it seems as though my user isn't logged in even if they are. That causes them not to redirect and stay on the login page until the state is updated in some way after the user object is initialized.
Firebase offers a way to fix this by giving us an onAuthStateChanged() method which allows me to execute a function when a user signs in or logs out.
What I'm doing now is using this method in the constructor method of my Login page class to manually re-render the component, thus redirecting the user when Firebase logs them in. It looks something like this:
export default class Login extends React.Component<Props, State> {
constructor(props:Props) {
super(props)
this.props.firebase.auth().onAuthStateChanged((user) => {
const oldState = this.state
this.setState(oldState)
})
}
render () {
if (this.props.firebase.auth().currentUser) {
return (
<Redirect to="/earn" />
)
} else {
return (
// Login page
)
}
}
}
(I omitted some irrelevant code)
Now this works fine and all but I'm not sure if this is the correct way to do it and I feel like I could make it look a lot nicer, I just don't know how.
Any suggestions or official ways to achieve what I'm doing right now are very much appreciated.

How to prevent to visit login page if user is logged in

How can I prevent to visit login page if user is logged in, I don't want to show user login page if user if user is not logged out. but I have tried with few step but it is not working for me.
I am storing static value in localstorage and if user try to come back into page login page then there I have created a function that user can visit to login page or not
login.js
componentWillMount(){
var id = localstorage.getitem('id')
if(id == "1"){
return <Redirect to="/dashboard"/>
}
}
Here I am able to get it and it going inside if condition as well but not redirecting to dashboard
I don't know what I am doing wrong here.
Your help would be highly appreciated
Thanks in Advance
Redirect works only when it is rendered, which means it is inside render or one of the functions called by it.
Returning a Redirect inside componentDidMount does not redirect the user. For use inside componentDidMount, you can use the imperative API:
this.props.history.push("/dashboard");
Docs for history
Note that this works only if the component is directly rendered inside a Route, otherwise props history will not be present. In other case, you can use withRouter higher order component.

Axios default headers cleared after page refresh in React.js

I am setting axios.defaults.headers.Authorization = MY_TOKEN in Login component which is rendered in Authentication component which checks if this.state.loggedin is set to true. If false it renders Login component, if true it renders UserComponent with BrowserRouter.
BrowserRouter reads "/" path and navigates to Documents component. During this navigation page refreshes and axios.defaults.headers.Authorization is cleared returning value of undefined. How can I preserve axios.defaults.headers even if page is refreshed or should I initialize default headers every time router navigates to other component?
UPDATE
Added some code how rendering happens in Authentication.js
render() {
return (
<UserNavigationContainer
{...this.props}
logout={this.onClickLogoutHandler}
/>
);
}
UserNavigationContainer.js renders routs (not complete code)
<BrowserRouter>
<div>
<UserNavigationComponent {...this.props}>
<Switch>
<Route
exact
path="/"
component={UserSubmittedDocumentsContainer}
/>
So actually when UserNavigationContainer gets rendered it navigates to "/" and refreshes page while navigating.
I had a similar experience and here is how I was able to solve it
Persist token to local storage on user login/signup:
the first step was to persist user token to local storage once login/signup succeeds, you can read up on the browser's local storage API here
Move logic that sets Authorization header to a component that always renders regardless of current path (Navigation bar component in my case):
next was to move the logic responsible for setting Authorization header to my Navigation bar component, by doing so, it automatically fetches the active user's token from local storage and sets the authorization header. now regardless of the component being rendered by react-router, authorization header is constantly being set, avoiding the need to do so for every other component.
PS: Moving the logic doesn't stop you from initially setting the authorization header inside the login component, it only solves the problem of doing so for every other component that gets rendered.
I have encountered the same issue. I solved my problem by setting the request common headers in root files. In my case it is index.js.
Do you notice that I am setting app_token from localStorage?
Initially, The AuthLayout renders the login component. If login success I have to redirect to the admin route.
Auth.js
So, I planned to set the headers in the login component. If login success I could able to set app_token in the request headers. All went well until I refresh the page.
Login.js
So, I set the token in localStorage and used it in the index.js to set the headers globally.
Login.js
I guess this is not a better solution. Well, I could able to set the headers globally and get authenticated using the token even after the page refresh.
UPDATE:
Another simple solution for setting authorization in headers is having an interceptor.
Step 1: Create a file called interceptor.js. Create an Instance.
const axios = require("axios");
const axiosApiInstance = axios.create();
// Request interceptor for API calls
axiosApiInstance.interceptors.request.use(
async (config) => {
config.headers = {
Authorization: `Bearer ${localStorage.getItem("token")}`,
};
return config;
},
(error) => {
Promise.reject(error);
}
);
export default axiosApiInstance;
step 2: Call your subsequent API's which require authorization headers as mentioned below.
import axiosApiInstance from "./interceptor";
let response = await axiosApiInstance.get(
"/api/***"
);
return response;
Thanks
Damali's answer is quite correct, but I also think it's worth expanding on this:
Move logic that sets Authorization header to a component that always
renders regardless of current path
To be honest, it's hard to understand much about OP's project structure, because the snippets posted for some reason relate to the auth-routing logic, which isn't the question asked. But, for clarity, elaborating on the above quote:
All authentication logic, including setting the axios header, should be encapsulated in a single component (probably a React Context). It is not as simple as "setting a header and passing go": any production-level app will need to:
Maintain some authentication state (logged in / out?)
Frequently evaluate that state (expired?)
Perhaps maintain and evaluate more detailed login info (eg roles)
Manipulate routing and API requests based on the above
This is the role of an auth module.
The auth module should control the axios authentication header. This means that we are almost certainly talking about two separate modules:
An HTTPs service module (contains and exports the axios instance), and
An auth module
Now: as OP more-or-less observed: if the auth module simply calls the axios instance and applies a header to it upon login, that will not persist after a refresh.
The trouble with Damali's answer is that even if your auth module is always rendered (eg it is at the very top of your app), the axios configuration will nevertheless not persist on page refresh. A page refresh will force a re-render: the header will be gone.
The answer is deceptively simple: re-apply the header every time auth is required (as well as on login). There are many ways to do this, here is just one:
// apiService.js
import Axios from 'axios';
const axios = Axios.create();
export function setDefaultHeader(key, value){
axios.defaults.headers.common[key] = value;
}
export axios;
// auth.js
import { axios, setDefaultHeader } from '../services/apiService.js';
const tokenKey = 'x-auth-token';
setDefaultHeader(tokenKey, localStorage[tokenKey]);
I had a similar problem and my resolve was to use both by retaining my previous model of adding token authorization once the user logs in normally and then doing the same in the index.js file. So, in the index.js file, I added the following:
// in case the page is reloaded, and the person is logged in, keep the authorization header
if (localStorage.getItem('token')) {
axios.defaults.headers.common["Authorization"] = "Token " + localStorage.getItem('token');
}
It first checks if there's a token. Therefore, when a page is reloaded, the axios settings will still remain.

Resources