react-router-dom#generatePath JavaScript Examples
The following examples show how to use
react-router-dom#generatePath.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: frontsiteUrls.js From react-invenio-app-ils with MIT License | 6 votes |
FrontSiteRoutesGenerators = {
documentsListWithQuery: (qs) =>
`${FrontSiteRoutesList.documentsList}?q=${qs}`,
documentDetailsFor: (documentPid) =>
generatePath(FrontSiteRoutesList.documentDetails, {
documentPid: documentPid,
}),
seriesDetailsFor: (seriesPid) =>
generatePath(FrontSiteRoutesList.seriesDetails, {
seriesPid: seriesPid,
}),
}
Example #2
Source File: ProvidersUrls.js From react-invenio-app-ils with MIT License | 6 votes |
ProviderRouteGenerators = {
providerDetailsFor: (providerPid) =>
generatePath(ProviderRoutesList.providerDetails, {
providerPid: providerPid,
}),
providerEditFor: (providerPid) =>
generatePath(ProviderRoutesList.providerEdit, {
providerPid: providerPid,
}),
providersListWithQuery: (qs) => `${ProviderRoutesList.providersList}?q=${qs}`,
}
Example #3
Source File: ILLUrls.js From react-invenio-app-ils with MIT License | 6 votes |
ILLRoutesGenerators = {
borrowingRequestListWithQuery: (qs) =>
`${ILLRoutesList.borrowingRequestList}?q=${qs}`,
borrowingRequestDetailsFor: (borrowingRequestPid) =>
generatePath(ILLRoutesList.borrowingRequestDetails, {
borrowingRequestPid: borrowingRequestPid,
}),
borrowingRequestEditFor: (borrowingRequestPid) =>
generatePath(ILLRoutesList.borrowingRequestEdit, {
borrowingRequestPid: borrowingRequestPid,
}),
}
Example #4
Source File: loan.js From react-invenio-app-ils with MIT License | 6 votes |
updateDates = async (
loanPid,
{
startDate = null,
endDate = null,
requestStartDate = null,
requestExpireDate = null,
} = {}
) => {
const payload = {};
if (startDate) {
payload.start_date = startDate;
}
if (endDate) {
payload.end_date = endDate;
}
if (requestStartDate) {
payload.request_start_date = requestStartDate;
}
if (requestExpireDate) {
payload.request_expire_date = requestExpireDate;
}
const path = generatePath(apiPaths.updateDates, {
loanPid: loanPid,
});
return await http.post(path, payload);
}
Example #5
Source File: Post.js From app with MIT License | 6 votes |
function Post({ title, author, slug, date, content }) {
const classes = useStyles();
return (
<>
<Typography
variant="h5"
className={classes.title}
gutterBottom
component={Link}
to={generatePath(BLOG_SINGLE_POST_PATH, { id: slug })}>
{title}
</Typography>
<br />
<Typography variant="subtitle2" color="textSecondary" gutterBottom>
By {author} – {date}
</Typography>
<Typography variant="body1" gutterBottom className={classes.content}>
{content}
</Typography>
<Typography variant="body2">
<Link to={generatePath(BLOG_SINGLE_POST_PATH, { id: slug })}>
Read more...
</Link>
</Typography>
</>
);
}
Example #6
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
removeProvider = async (docReqPid) => {
const url = generatePath(apiPaths.provider, { docReqPid: docReqPid });
return await http.delete(url);
}
Example #7
Source File: backofficeUrls.js From react-invenio-app-ils with MIT License | 5 votes |
BackOfficeRouteGenerators = {
documentEditFor: (documentPid) =>
generatePath(BackOfficeRoutesList.documentEdit, {
documentPid: documentPid,
}),
documentsListWithQuery: (qs) =>
`${BackOfficeRoutesList.documentsList}?q=${qs}`,
documentDetailsFor: (documentPid) =>
generatePath(BackOfficeRoutesList.documentDetails, {
documentPid: documentPid,
}),
documentRequestsListWithQuery: (qs) =>
`${BackOfficeRoutesList.documentRequestsList}?q=${qs}`,
documentRequestDetailsFor: (documentRequestPid) =>
generatePath(BackOfficeRoutesList.documentRequestDetails, {
documentRequestPid: documentRequestPid,
}),
documentRequestEditFor: (documentRequestPid) =>
generatePath(BackOfficeRoutesList.documentRequestEdit, {
documentRequestPid: documentRequestPid,
}),
eitemDetailsFor: (eitemPid) =>
generatePath(BackOfficeRoutesList.eitemDetails, { eitemPid: eitemPid }),
eitemEditFor: (eitemPid) =>
generatePath(BackOfficeRoutesList.eitemEdit, { eitemPid: eitemPid }),
eitemsListWithQuery: (qs) => `${BackOfficeRoutesList.eitemsList}?q=${qs}`,
itemsListWithQuery: (qs) => `${BackOfficeRoutesList.itemsList}?q=${qs}`,
itemDetailsFor: (itemPid) =>
generatePath(BackOfficeRoutesList.itemDetails, { itemPid: itemPid }),
itemEditFor: (itemPid) =>
generatePath(BackOfficeRoutesList.itemEdit, { itemPid: itemPid }),
loansListWithQuery: (qs) => `${BackOfficeRoutesList.loansList}?q=${qs}`,
loanDetailsFor: (loanPid) =>
generatePath(BackOfficeRoutesList.loanDetails, { loanPid: loanPid }),
ilocationsEditFor: (ilocationPid) =>
generatePath(BackOfficeRoutesList.ilocationsEdit, {
ilocationPid: ilocationPid,
}),
locationsEditFor: (locationPid) =>
generatePath(BackOfficeRoutesList.locationsEdit, {
locationPid: locationPid,
}),
locationsDetailsFor: (locationPid) =>
generatePath(BackOfficeRoutesList.locationsDetails, {
locationPid: locationPid,
}),
patronDetailsFor: (patronPid) =>
generatePath(BackOfficeRoutesList.patronDetails, { patronPid: patronPid }),
seriesListWithQuery: (qs) => `${BackOfficeRoutesList.seriesList}?q=${qs}`,
seriesDetailsFor: (seriesPid) =>
generatePath(BackOfficeRoutesList.seriesDetails, { seriesPid: seriesPid }),
seriesEditFor: (seriesPid) =>
generatePath(BackOfficeRoutesList.seriesEdit, {
seriesPid: seriesPid,
}),
}
Example #8
Source File: AcquisitionUrls.js From react-invenio-app-ils with MIT License | 5 votes |
AcquisitionRouteGenerators = {
orderDetailsFor: (orderPid) =>
generatePath(AcquisitionRoutesList.orderDetails, { orderPid: orderPid }),
orderEditFor: (orderPid) =>
generatePath(AcquisitionRoutesList.orderEdit, { orderPid: orderPid }),
ordersListWithQuery: (qs) => `${AcquisitionRoutesList.ordersList}?q=${qs}`,
}
Example #9
Source File: urls.js From react-invenio-app-ils with MIT License | 5 votes |
AuthenticationRoutesGenerators = {
redirectAfterLogin: (nextUrl) =>
generatePath(AuthenticationRoutesList.redirectUrlAfterLogin, {
nextUrl: nextUrl,
}),
}
Example #10
Source File: loan.js From react-invenio-app-ils with MIT License | 5 votes |
sendOverdueLoansNotificationReminder = async (payload) => {
const path = generatePath(apiPaths.notificationOverdue, {
loanPid: payload.loanPid,
});
return await http.post(path, payload);
}
Example #11
Source File: loan.js From react-invenio-app-ils with MIT License | 5 votes |
assignItemToLoan = async (itemPid, loanPid) => {
const path = generatePath(apiPaths.replaceItem, { loanPid: loanPid });
const payload = { item_pid: itemPid };
const response = await http.post(path, payload);
response.data = serializer.fromJSON(response.data);
return response;
}
Example #12
Source File: loan.js From react-invenio-app-ils with MIT License | 5 votes |
get = async (loanPid) => {
const path = generatePath(apiPaths.item, { loanPid: loanPid });
const response = await http.get(path);
response.data = serializer.fromJSON(response.data);
return response;
}
Example #13
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
decline = async (docRequestPid, data) => {
const urlPath = generatePath(apiPaths.decline, { docReqPid: docRequestPid });
return performAction(urlPath, data);
}
Example #14
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
addProvider = async (docReqPid, data) => {
const url = generatePath(apiPaths.provider, { docReqPid: docReqPid });
return await http.post(url, data);
}
Example #15
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
removeDocument = async (docReqPid, data) => {
const url = generatePath(apiPaths.document, { docReqPid: docReqPid });
// https://github.com/axios/axios/issues/897#issuecomment-343715381
return await http.delete(url, { data: data });
}
Example #16
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
addDocument = async (docReqPid, data) => {
const url = generatePath(apiPaths.document, { docReqPid: docReqPid });
return await http.post(url, data);
}
Example #17
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
accept = async (docRequestPid) => {
const urlPath = generatePath(apiPaths.accept, { docReqPid: docRequestPid });
return performAction(urlPath);
}
Example #18
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
del = async (docRequestPid) => {
const path = generatePath(apiPaths.item, { docReqPid: docRequestPid });
const response = await http.delete(path);
return response;
}
Example #19
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
get = async (docRequestPid) => {
const path = generatePath(apiPaths.item, { docReqPid: docRequestPid });
const response = await http.get(path);
response.data = serializer.fromJSON(response.data);
return response;
}
Example #20
Source File: documentRequest.js From react-invenio-app-ils with MIT License | 5 votes |
update = async (docRequestPid, data) => {
const path = generatePath(apiPaths.item, { docReqPid: docRequestPid });
const response = await http.put(path, data);
response.data = serializer.fromJSON(response.data);
return response;
}
Example #21
Source File: MapMarker.js From app with MIT License | 5 votes |
function MapMarker({ request, clusterer, position }) {
const [marker, setMarker] = useState(null);
const [showInfoWindow, setShowInfoWindow] = useState(false);
const handleOnLoad = (mapMarker) => {
setMarker(mapMarker);
};
const handleOnClick = () => {
setShowInfoWindow(!showInfoWindow);
};
const renderInfoWindow = (mapMarker) => {
if (mapMarker === null || request === null || !showInfoWindow) return null;
// TODO: Remove this once the model has stabilized.
if (!request || !request.d) return null;
return (
<InfoWindow anchor={mapMarker}>
<div>
<Typography variant="subtitle2">
{request.d.firstName} – {request.d.generalLocationName}
</Typography>
<Typography variant="body2">
{format(request.d.createdAt.toDate(), 'p - PPPP')}
</Typography>
<Typography variant="body2">
Immediacy:{' '}
{immediacyMap[request.d.immediacy] &&
immediacyMap[request.d.immediacy].shortDescription}
</Typography>
<Typography variant="body2">
Needs:{' '}
{request.d.needs.map((key) => allCategoryMap[key].shortDescription)}
</Typography>
<Typography variant="subtitle2">
<Link to={generatePath(REQUEST_PATH, { requestId: request.id })}>
Details...
</Link>
</Typography>
</div>
</InfoWindow>
);
};
return (
<Marker
clusterer={clusterer}
position={position}
onClick={handleOnClick}
onLoad={handleOnLoad}>
{renderInfoWindow(marker)}
</Marker>
);
}
Example #22
Source File: SearchPage.js From app with MIT License | 4 votes |
function SearchPage() {
const classes = useStyles();
const { showError } = useNotifications();
// State
const [showAddressPicker, setShowAddressPicker] = useState(false);
const [nearbyRequests, setNearbyRequests] = useState(null);
const [currentLatLong, setCurrentLatLong] = useState({
latitude: DEFAULT_LATITUDE,
longitude: DEFAULT_LONGITUDE,
});
const [currentPlaceLabel, setCurrentPlaceLabel] = React.useState(
`Using default location: ${DEFAULT_LOCATION_NAME}`,
);
const [distance, setDistance] = useState(defaultDistance);
const [searching, setSearching] = useState(false);
const [onSearch$] = useState(() => new Subject());
// Data
const user = useUser();
const firestore = useFirestore();
const analytics = useAnalytics();
const { GeoPoint } = useFirestore;
async function searchForNearbyRequests({ searchLocation, searchDistance }) {
if (!searchLocation) return;
// Use lat/long set to state (either from profile or default)
const { latitude, longitude } = searchLocation;
setSearching(true);
analytics.logEvent('search', {
search_term: `latitude=${latitude}&longitude=${longitude}`,
});
try {
// Query for nearby requests
const geofirestore = new GeoFirestore(firestore);
const nearbyRequestsSnap = await geofirestore
.collection(REQUESTS_PUBLIC_COLLECTION)
.near({
center: new GeoPoint(latitude, longitude),
radius: KM_TO_MILES * searchDistance,
})
.where('status', '==', 1)
.limit(30)
.get();
const sortedByDistance = nearbyRequestsSnap.docs.sort(
(a, b) => a.distance - b.distance,
);
setNearbyRequests(
sortedByDistance.map((docSnap) => ({
...docSnap.data(),
id: docSnap.id,
distance: kmToMiles(docSnap.distance).toFixed(2),
})),
);
setSearching(false);
} catch (err) {
showError('Error searching for nearby requests');
// eslint-disable-next-line no-console
console.log(err);
setSearching(false);
}
}
// Setup an observable for debouncing the search requests.
useEffect(() => {
const subscription = onSearch$
.pipe(debounceTime(500))
.subscribe(searchForNearbyRequests);
return () => subscription.unsubscribe();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// This pushes new empty values to the observable when the distance or location changes.
useEffect(() => {
onSearch$.next({
searchLocation: currentLatLong,
searchDistance: distance,
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentLatLong, distance]);
useEffect(() => {
async function loadLatLongFromProfile() {
// TODO: Search is triggered twice when the user is logged in. Once with the first render,
// and then again when the user is assigned. Need to fix this behavior.
// Set lat/long from profile or fallback to defaults
if (user && user.uid) {
const profileRef = firestore.doc(`${USERS_COLLECTION}/${user.uid}`);
const profileSnap = await profileRef.get();
const geopoint = profileSnap.get('preciseLocation');
if (geopoint) {
const userLocation = {
latitude: geopoint.latitude,
longitude: geopoint.longitude,
};
setCurrentLatLong(userLocation);
setCurrentPlaceLabel(
`Near ${profileSnap.get('generalLocationName')}`,
);
onSearch$.next({
searchLocation: userLocation,
searchDistance: defaultDistance,
});
} else {
onSearch$.next({
searchLocation: currentLatLong,
searchDistance: defaultDistance,
});
}
} else {
onSearch$.next({
searchLocation: currentLatLong,
searchDistance: defaultDistance,
});
}
}
// NOTE: useEffect is used to load data so it can be done conditionally based
// on whether current user is logged in
loadLatLongFromProfile();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [user]);
function handleCopyNeedLink(id) {
const el = document.createElement('textarea');
document.body.appendChild(el);
el.value = `${window.location.origin}${generatePath(REQUEST_PATH, {
requestId: id,
})}`;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
// Gets the lat/lng for the selected address.
function handlePlaceSelect(_event, selection) {
if (!selection) return;
geocodeByAddress(selection.description)
.then((results) => getLatLng(results[0]))
.then((latLng) => {
setCurrentLatLong({ latitude: latLng.lat, longitude: latLng.lng });
})
.catch((error) => {
showError('Failed to get the location from address.');
// eslint-disable-next-line no-console
console.error('Error', error);
});
}
function handlePlaceChange(address) {
setCurrentPlaceLabel(address);
}
return (
<Container maxWidth="md">
<Helmet>
<title>Find Opportunities</title>
</Helmet>
<Typography variant="h6">Search Criteria</Typography>
<Paper className={classes.filterPaper}>
{!showAddressPicker && (
<div className={classes.searchLocation}>
<Typography id="continuous-slider">{currentPlaceLabel}</Typography>
<Button
data-test="new-location-button"
onClick={() => setShowAddressPicker(true)}
className={classes.enterAddressButton}>
Select new location
</Button>
</div>
)}
{showAddressPicker && (
<>
<LoadScript
id="script-loader"
libraries={USED_GOOGLE_MAPS_LIBRARIES}
googleMapsApiKey={process.env.REACT_APP_FIREBASE_API_KEY}>
<PlacesAutocomplete
value={currentPlaceLabel}
onChange={handlePlaceChange}>
{({ getInputProps, suggestions, loading }) => (
<>
{/* {console.log(suggestions)} */}
<Autocomplete
data-test="places-autocomplete"
onChange={handlePlaceSelect}
options={suggestions}
loading={loading}
getOptionLabel={(sug) => sug.description}
noOptionsText="No matches"
renderInput={(params) => (
<TextField
margin="none"
data-test="address-entry"
{...getInputProps({
...params,
label: 'Address',
className: classes.searchInput,
})}
InputProps={{
...params.InputProps,
endAdornment: (
<>
{loading && (
<CircularProgress color="inherit" size={20} />
)}
</>
),
}}
/>
)}
/>
</>
)}
</PlacesAutocomplete>
</LoadScript>
<Typography align="right" variant="caption" display="block">
Powered by Google Maps
</Typography>
</>
)}
<Divider className={classes.divider} />
<Typography id="continuous-slider" gutterBottom>
Distance (in miles)
</Typography>
<div className={classes.distance}>
<Slider
defaultValue={defaultDistance}
valueLabelDisplay="on"
// valueLabelFormat={x => `${x} mi`}
marks={markValues}
onChange={(_event, value) => setDistance(value)}
min={1}
max={markValues[markValues.length - 1].value}
/>
</div>
</Paper>
{searching && (
<Paper className={classes.simplePaper}>
<LinearProgress />
</Paper>
)}
{nearbyRequests && nearbyRequests.length === 0 && (
<Paper className={classes.simplePaper}>
<Typography data-test="no-requests-found">
No requests found with {distance} miles. You can try expanding the
search area or try entering a new location.
</Typography>
</Paper>
)}
{nearbyRequests &&
nearbyRequests.map((result) => (
<Paper className={classes.resultPaper} key={result.id}>
<Grid container>
<Hidden xsDown>
<Grid item className={classes.distanceContainer} sm={2}>
{result.distance}
<br />
miles
</Grid>
</Hidden>
<Grid item className={classes.requestSummary} xs={12} sm={10}>
{parseInt(result.immediacy, 10) > 5 && (
<img
align="right"
src="/taskIcon.png"
width="50px"
height="50px"
alt="Urgent"
title="Urgent"
/>
)}
<Typography variant="h6">
{result.name ? result.name : result.firstName} –{' '}
{result.generalLocationName}
</Typography>
<Typography variant="caption" gutterBottom>
Requested {format(result.createdAt.toDate(), 'p - PPPP')}
</Typography>
<Typography variant="h5" className={classes.needs} gutterBottom>
{result.needs.map((item) => (
<React.Fragment key={item}>
{allCategoryMap[item] ? (
<Chip
size="small"
variant="outlined"
icon={
item === 'grocery-pickup' ? <GroceryIcon /> : null
}
label={allCategoryMap[item].shortDescription}
/>
) : (
<Alert severity="error">
Could not find '{item}' in all category map.
</Alert>
)}
</React.Fragment>
))}
{result.needFinancialAssistance && (
<Chip
variant="outlined"
size="small"
icon={<FinancialAssitanceIcon />}
label="Need financial assistance"
/>
)}
</Typography>
<Hidden smUp>
<Typography
align="right"
variant="h5"
className={classes.TaskTitle}>
{result.distance} miles
</Typography>
</Hidden>
<Grid container justify="flex-end">
<Grid item>
{navigator.share ? (
<Button
size="small"
onClick={() => {
navigator.share({
title: 'CV19 Assist Need Link',
text: 'CV19 Assist Need Link',
url: `${window.location.origin}${generatePath(
REQUEST_PATH,
{
requestId: result.id,
},
)}`,
});
}}>
SHARE
</Button>
) : (
<Button
size="small"
onClick={() => handleCopyNeedLink(result.id)}>
COPY LINK FOR SHARING
</Button>
)}{' '}
<Button
component={Link}
to={generatePath(REQUEST_PATH, {
requestId: result.id,
})}
size="small"
color="primary"
disableElevation>
DETAILS...
</Button>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
))}
</Container>
);
}
Example #23
Source File: RequestSuccessfulPage.js From app with MIT License | 4 votes |
function RequestSuccessfulPage() {
const classes = useStyles();
const location = useLocation();
const qs = queryString.parse(location.search);
const requestId = (qs && qs.id) || null;
return (
<>
<Helmet>
<title>Request Submitted</title>
</Helmet>
<Container maxWidth="md">
<Typography variant="h5" gutterBottom>
We have sucessfully submitted your request
</Typography>
<Paper className={classes.container}>
<Typography variant="h5" color="textSecondary" paragraph>
Here’s what to expect
</Typography>
<ol>
<li>
You’ll get a phone call from a volunteer in your area who will be
assisting with your task, so you can confirm for them exactly what
you need and where you need it from.
</li>
<li>
If you are asking the volunteer to buy something for you, you can
choose to pay in one of three ways:
<ol>
<li>
Call the store in advance to place the order and pay with your
credit card over the phone, letting them know someone else
will be picking it up on your behalf.
</li>
<li>
Provide your volunteer with cash before or after they complete
the order. Make sure to leave the cash by the front door to
avoid physical contact.
</li>
<li>
Reimburse the volunteer using an online method such as Paypal
or Venmo.
</li>
</ol>
</li>
<li>
Whatever payment method you select, your volunteer will include
your receipt in the delivery bag and leave the bag at your
doorstep, ringing your bell so you know it has arrived.
</li>
</ol>
{/* TODO: do we really want to provide any guidance for folks that are experiencing symptoms?
<Typography>
PLEASE NOTE: If you are experiencing symptoms of COVID-19, we ask that
you not reimburse your volunteer in cash but through Venmo, another
payment app, or call ahead to the store. Please do not open the door
until the volunteer has left the premises.
</Typography> */}
<Typography gutterBottom>
Please note that we will try our best to match you with a volunteer,
but we cannot guarantee that we will find a match.
</Typography>
<Typography gutterBottom>Stay safe!</Typography>
<div className={classes.buttons}>
{requestId && (
<Button
component={Link}
to={generatePath(REQUEST_PATH, { requestId })}
variant="contained"
disableElevation>
View Your Request
</Button>
)}
<Button
component={Link}
to="/"
variant="contained"
color="primary"
disableElevation
startIcon={<HomeIcon />}>
Home
</Button>
</div>
</Paper>
</Container>
</>
);
}