change profile picture when click in link to the same page - javascript

I have an user profile (/someuser) that I open using :
<Route path="/:user" component={Profile} />
The profile is like this:
export default function App(props) {
const [nick, setNick] = useState(props.match.params.user); //get the nick using props.
const [profile, setProfile_picture] = useState(profile_picture); // default one
useEffect(() => {
// get current user profile picture:
firebase.database().ref('/users/').orderByChild('user').equalTo(props.match.params.user).once('value').then(snapshot => {
if (snapshot.exists()){
var img = snapshot.val().img;
setProfile_picture(img);
}
});
}, []);
return(
<>
<img className={classes.profile} src={profile} />
<h1>{nick}</h1>
<Link to="/user2">Go to profile 2</Link>
</>
);
}
);
Supose I'm in /user profile and I click in the Link at the end of the code to go to the /user2. What I'd like to do is change the profile picture and the nick (without reload). Force after click to update this informations... Any ideas how can I do this?
Thanks.

You need to trigger the useEffect based on params change because when the params change component is re-rendered by react-router and hence the state will not be re-initialized.
Triggering the useEffect on params change will ensure data is updated when params change.
Also make sure to set nick state too ni useEffect as that too needs to update on params change
useEffect(() => {
// set nick state
setNick(props.match.params.user);
// get current user profile picture:
firebase.database().ref('/users/').orderByChild('user').equalTo(props.match.params.user).once('value').then(snapshot => {
if (snapshot.exists()){
var img = snapshot.val().img;
setProfile_picture(img);
}
});
}, [props.match.params.user]);

Do you mean without reloading the page? If so then I think you can make a boolean that toggles when you go to a different route and initiates then useEffect hook by putting it in the dependency array. Or you could move the code to a separate component and pass it in as a prop. Now to do it completely without redirecting the browser would be to use the toggle boolean as mentioned before, but using fetch api, axios, etc to send that nick to a backend and change it accordingly which I think is similar to an Ajax request I hope this helps.

Related

Access Stripe Payment Element's loading state

In my Reactjs app, I'm using the payment intent API from stripe to handle payments. I use the embeddable Payment Element <PaymentElement /> from #stripe/react-stripe-js to render the UI but the problem is that it takes a couple of seconds before the Payment Element is fully loaded in the UI.
Is there any way I can access its loading state and show a loading spinner while it's being loaded?
Stripe just added a new loader option to their PaymentElement product documented here. It allows you to have a skeleton render first while the UI is loading which should solve the problem you were going for.
Alternatively, you can listen to their ready event documented here so that you show a loading animation until the event is fired.
While this is for their vanilla JS integration, you can use those with their React library since you control which option to pass on the PaymentElement on initialization.
For anyone not content with simply using their loader, you can listen to the ready event (docs).
To do this, you have to get the element first, which is a step that confused me. You should have the elements reference from the useElements hook. In useEffect you can try to do elements.getElement('paymentMethod') but you will get an error saying:
A valid Element name must be provided. Valid Elements are: card,
cardNumber, cardExpiry, cardCvc, postalCode, paymentRequestButton,
iban, idealBank, p24Bank, auBankAccount, fpxBank, affirmMessage,
afterpayClearpayMessage; you passed: paymentElement.
However, the correct thing to get is payment despite not being in that list:
const element = elements.getElement('payment')
element.on('ready', () => {
console.log("READY")
})
Thanks #Yeats on ready solved this for me - great answer.
I want to add for anyone looking at this solution that you should not hide your until the on ready state returns. I mistakenly used a useState variable to show a loader until PaymentElement was ready, but realised that only the loader component needed to be toggled by state and that the PaymentElement should be rendered always. My first try I hid the PaymentElement from render using my loading state var like this:
Don't do this!
{isStripLoading ? (
<MyLoaderComponent />
) : (
<PaymentElement />
)}
So, assuming you have a state variable isStripeLoading default to true and you have useEffect on ready event setIsStripeLoading(false) then wrap only you loader spinner component in the isStripeLoading state variable and NOT the PaymentElement component.
Example
const stripe = useStripe()
const elements = useElements()
const [isStripeLoading, setIsStripLoading] = useState(true)
useEffect(() => {
if (elements) {
const element = elements.getElement('payment')
element.on('ready', () => {
setIsStripLoading(false)
})
}
}, [elements])
return (
<form id='payment-form' onSubmit={handleSubmit}>
{isStripeLoading && <MyLoaderComponent />}
<PaymentElement id='payment-element'/>
<button id='submit' disabled={!stripe || !elements}>Pay</button>
</form>
)

How can I change state before link works at react-router-dom

I have to get information about user before link work and I don't Know how can I do this.
It is not all my code but similar. On click I have to get info and then give it to component in which I link to, but link works first and info does not have time to geted.
const [userId, setUserId] = useState(null);
const filterUserbyId = (id) => {
setUserId(id);
}
return(
<Link
onClick={()=>filterUserbyId(props.id)}
to={{
pathname: `/user/${props.id}`,
state: {
userId: userId
}
}}>
)
Also this is the warning but it says exactly that I tell above
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect
cleanup function.
You have over-complicated such a simple task.
Instead of trying to fetch the data from the database and then pass that fetched data to the new component to which you will redirect to, you could just pass the user id as a URL parameter
return(
<Link to={`/user/${props.id}`} />
);
In the other component, extract the user id from the URL parameter using the useParams() hook
const { userID } = useParams();
Note: userID is the dynamic route parameter. For the above statement to work, route to this component should be defined as:
<Route path="/user/:userID" component={/* insert component name */}/>
Once you have the user id, use the useEffect() hook to fetch the data from the database and display it to the user.
useEffect(() => {
// fetch the data here
}, []);
Alternative Solution - (not recommended)
You could also do it the way originally tried but for this to work, you need to change the Link component to a normal button element and when that button is clicked, fetch the data from the database and then programmatically change the route using the useHistory() hook, passing along the fetched data to the new route.
const routerHistory = useHistory();
const filterUserbyId = (id) => {
// fetch user data
...
// redirect to another route
routerHistory.push(`/user/${props.id}`, { state: data });
}
return(
<button onClick={() => filterUserbyId(props.id)}>
Button
</button>
)
I suggest that you don't use this solution because you don't want to wait for the data to be fetched from the database before changing the route. Route should be changed as soon as user clicks and data should be fetched inside the new component.

how to re render component on Link click [duplicate]

Is there a way to force a React-Router <Link> to load a page from path, even when the current location is already that page? I can't seem to find any mention of this in the react-router documentations.
We have a page on a route for "apply" that loads up a landing page with a hero image, some explanatory text, etc., and an "apply for this program" button that swaps in content that acts as an application form. This all happens on the same "apply" route, because users should not be able to directly navigate to this form without first hitting the landing page.
However, when they have this form open, and they click on the apply link in the nav menu again, the entire page should reload as it would on first mount, getting them "back" (but really, forward) to the landing page again.
Instead, clicking the <Link> does nothing, because react-router sees we're already on the "apply" page, and so does not unmount the current page to then mount a different one.
Is there a way to force it to unmount the current page before then mounting the requested page, even if it's for the page users are supposedly already on? (via a <Link> property for instance?)
Note: this question was posted when React-Router meant v5, and while the problem in this post is independent of a specific React-Router versions, but the solutions are not. As such, the accepted answer is the solution for React-Router v6, so if you're still using v5, first and foremost upgrade your version of React-Router, but if you absolutely can't, the accepted answer won't work for you and you'll want this answer instead.
In the Route component, specify a random key.
<Route path={YOURPATH} render={(props) => <YourComp {...props} keyProp={someValue} key={randomGen()}/>} />
when react see a different key, they will trigger rerender.
A fix I used to solve my little need around this was to change the location that React-Router looks at. If it sees a location that we're already on (as in your example) it won't do anything, but by using a location object and changing that, rather than using a plain string path, React-Router will "navigate" to the new location, even if the path looks the same.
You can do this by setting a key that's different from the current key (similar to how React's render relies on key) with a state property that allows you to write clear code around what you wanted to do:
render() {
const linkTarget = {
pathname: "/page",
key: uuid(), // we could use Math.random, but that's not guaranteed unique.
state: {
applied: true
}
};
return (
...
<Link to={linkTarget}>Page</Link>
...
);
}
Note that (confusingly) you tell the Link which values you need pass as a state object, but the link will pass those values on into the component as props. So don't make the mistake of trying to access this.state in the target component!
We can then check for this in the target component's componentDidUpdate like so:
componentDidUpdate(prevProps, prevState, snapshot) {
// Check to see if the "applied" flag got changed (NOT just "set")
if (this.props.location.state.applied && !prevProps.location.state.applied) {
// Do stuff here
}
}
Simple as:
<Route path="/my/path" render={(props) => <MyComp {...props} key={Date.now()}/>} />
Works fine for me. When targeting to the same path:
this.props.history.push("/my/path");
The page gets reloaded, even if I'm already at /my/path.
Based on official documentation for 'react-router' v6 for Link component
A is an element that lets the user navigate to another page by clicking or tapping on it. In react-router-dom, a renders an accessible element with a real href that points to the resource it's linking to. This means that things like right-clicking a work as you'd expect. You can use to skip client side routing and let the browser handle the transition normally (as if it were an ).
So you can pass reloadDocument to your <Link/> component and it will always refresh the page.
Example
<Link reloadDocument to={linkTo}> myapp.com </Link>
At least works for me!
Not a good solution because it forces a full page refresh and throws an error, but you can call forceUpdate() using an onClick handler like:
<Link onClick={this.forceUpdate} to={'/the-page'}>
Click Me
</Link>
All I can say is it works. I'm stuck in a similar issue myself and hope someone else has a better answer!
React router Link not causing component to update within nested routes
This might be a common problem and I was looking for a decent solution to have in my toolbet for next time. React-Router provides some mechanisms to know when an user tries to visit any page even the one they are already.
Reading the location.key hash, it's the perfect approach as it changes every-time the user try to navigate between any page.
componentDidUpdate (prevProps) {
if (prevProps.location.key !== this.props.location.key) {
this.setState({
isFormSubmitted: false,
})
}
}
After setting a new state, the render method is called. In the example, I set the state to default values.
Reference: A location object is never mutated so you can use it in the lifecycle hooks to determine when navigation happens
I solved this by pushing a new route into history, then replacing that route with the current route (or the route you want to refresh). This will trigger react-router to "reload" the route without refreshing the entire page.
<Link onClick={this.reloadRoute()} to={'/route-to-refresh'}>
Click Me
</Link>
let reloadRoute = () => {
router.push({ pathname: '/empty' });
router.replace({ pathname: '/route-to-refresh' });
}
React router works by using your browser history to navigate without reloading the entire page. If you force a route into the history react router will detect this and reload the route. It is important to replace the empty route so that your back button does not take you to the empty route after you push it in.
According to react-router it looks like the react router library does not support this functionality and probably never will, so you have to force the refresh in a hacky way.
I got this working in a slightly different way that #peiti-li's answer, in react-router-dom v5.1.2, because in my case, my page got stuck in an infinite render loop after attempting their solution.
Following is what I did.
<Route
path="/mypath"
render={(props) => <MyComponent key={props.location.key} />}
/>
Every time a route change happens, the location.key prop changes even if the user is on the same route already. According to react-router-dom docs:
Instead of having a new React element created for you using the
component prop, you can pass in a function to be called when the
location matches. The render prop function has access to all the same
route props (match, location and history) as the component render
prop.
This means that we can use the props.location.key to obtain the changing key when a route change happens. Passing this to the component will make the component re-render every time the key changes.
I found a simple solution.
<BrowserRouter forceRefresh />
This forces a refresh when any links are clicked on. Unfortunately, it is global, so you can't specify which links/pages to refresh only.
From the documentation:
If true the router will use full page refreshes on page navigation. You may want to use this to imitate the way a traditional server-rendered app would work with full page refreshes between page navigation.
Here's a hacky solution that doesn't require updating any downstream components or updating a lot of routes. I really dislike it as I feel like there should be something in react-router that handles this for me.
Basically, if the link is for the current page then on click...
Wait until after the current execution.
Replace the history with /refresh?url=<your url to refresh>.
Have your switch listen for a /refresh route, then have it redirect back to the url specified in the url query parameter.
Code
First in my link component:
function MenuLink({ to, children }) {
const location = useLocation();
const history = useHistory();
const isCurrentPage = () => location.pathname === to;
const handler = isCurrentPage() ? () => {
setTimeout(() => {
if (isCurrentPage()) {
history.replace("/refresh?url=" + encodeURIComponent(to))
}
}, 0);
} : undefined;
return <Link to={to} onClick={handler}>{children}</Link>;
}
Then in my switch:
<Switch>
<Route path="/refresh" render={() => <Redirect to={parseQueryString().url ?? "/"} />} />
{/* ...rest of routes go here... */}
<Switch>
...where parseQueryString() is a function I wrote for getting the query parameters.
There is a much easier way now to achieve this, with the reloadDocument Link prop:
<Link to={linkTarget} reloadDocument={true}>Page</Link>
you can use BrowserRouter forceRefresh={true}
I use react-router-dom 5
Example :
<BrowserRouter forceRefresh={true}>
<Link
to={{pathname: '/otherPage', state: {data: data}}}>
</Link>
</BrowserRouter>
Solved using the Rachita Bansal answer but with the componentDidUpdate instead componentWillReceiveProps
componentDidUpdate(prevProps) {
if (prevProps.location.pathname !== this.props.location.pathname) { window.location.reload();
}
}
You can use the lifecycle method - componentWillReceiveProps
When you click on the link, the key of the location props is updated. So, you can do a workaround, something like below,
/**
* #param {object} nextProps new properties
*/
componentWillReceiveProps = (nextProps)=> {
if (nextProps.location.pathname !== this.props.location.pathname) {
window.location.reload();
}
};
To be honest, none of these are really "thinking React". For those that land on this question, a better alternative that accomplishes the same task is to use component state.
Set the state on the routed component to a boolean or something that you can track:
this.state = {
isLandingPage: true // or some other tracking value
};
When you want to go to the next route, just update the state and have your render method load in the desired component.
Try just using an anchor tag a href link. Use target="_self" in the tag to force the page to rerender fully.

How to find Popup state and refresh state in React-router?

I know this question kind a stupid But I am pretty confused with this site producthunt how they are doing this.When clicking the product list popup with react router is done like this..
But When I refresh that page it render like this..How this is done using React-router
My bet would be that they use the state property when pushing a page to give an indication to the component about how to render the page. More specifically, to indicate the component where it comes from. For example:
router.push({
pathname: '/posts/origami-studio-by-facebook',
state: { fromPosts: true }
})
And then you can read the router's state in the route's component to check what page to show.
const Post = (productName) => {
if(this.context.router.location.state.fromPosts) {
return <Posts productPopup{productName} />
// open the posts page with a popup for the product
} else {
return <PostPage productName={productName} />
}
}
So when you open the page in your browser, the state.fromPosts is not set and you get redirected to the PostPage. In the end, even if the route is the same, what you end up seing is completely different.

ReactJS: save state when navigate with browser button

My app has two pages, first, the home page, which is a list of items, loaded with ajax, and support pagination. when you click an item in the list, it will render a new page, shows the detail of the item. I'm using react-router and it works fine.
However, when I press back button, I'll get back to the home page, and all the previous state is lost, I have to wait for ajax load again, and lost the pagination too.
So, how can I improve this, let the page act as an ordinary one (when you press back button you can return to the previous state instantly, even with the same scroll position), thanks.
I've solved this myself by providing a module Store, which is like this:
// Store.js
var o = {};
var Store = {
saveProductList: function(state) {
o['products'] = state;
},
getProductList: function() {
return o['products'];
}
};
module.exports = Store;
then in the home page component, load and save the state:
componentDidMount: function() {
var state = Store.getProductList();
if (state) {
this.setState(state);
} else {
// load data via ajax request
}
},
componentWillUnmount: function() {
Store.saveProductList(this.state);
}
this works for me.
You should use dynamic routes like this example:
<Route name="inbox" handler={Inbox}>
<Route name="message" path=":messageId" handler={Message}/>
<DefaultRoute handler={InboxStats}/>
</Route>
If you change the messageId(child component) you will still have the same state in the Inbox(parent) Component.
It will look something like this:
<Route name="search" path="/search/:query?/:limit?/:offset?" handler={Search} />

Categories