refactor(phone/marketplace): Refactor state management and fetching

This commit is contained in:
Taso committed 2021-06-08 15:46:39 -04:00
1 parent 2d1e192892
commit 4afa9c691b
12 files changed
+210 -86

No files matched your search

@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { AppWrapper } from '../../../ui/components'; import { AppWrapper } from '../../../ui/components';
import { AppContent } from '../../../ui/components/AppContent'; import { AppContent } from '../../../ui/components/AppContent';
import { MarketplaceListContainer } from './SelloutList/MarketplaceListContainer'; import { MarketplaceListContainer } from './MarketplaceList/MarketplaceListContainer';
import { NavigationBar } from './navigation/NavigationBar'; import { NavigationBar } from './navigation/NavigationBar';
import { Switch, Route } from 'react-router-dom'; import { Switch, Route } from 'react-router-dom';
import { ListingFormContainer } from './form/ListingFormContainer'; import { ListingFormContainer } from './form/ListingFormContainer';
@@ -1,7 +1,11 @@
import { Box, Tooltip, Button } from '@material-ui/core'; import { Box, Tooltip, Button } from '@material-ui/core';
import { makeStyles, Theme } from '@material-ui/core/styles'; import { makeStyles, Theme } from '@material-ui/core/styles';
import React from 'react'; import React from 'react';
import { MarketplaceEvents, MarketplaceListing } from '../../../../../../typings/marketplace'; import {
MarketplaceActionResp,
MarketplaceEvents,
MarketplaceListing,
} from '../../../../../../typings/marketplace';
import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; import { useSimcard } from '../../../../os/simcard/hooks/useSimcard';
import DeleteIcon from '@material-ui/icons/Delete'; import DeleteIcon from '@material-ui/icons/Delete';
import ReportIcon from '@material-ui/icons/Report'; import ReportIcon from '@material-ui/icons/Report';
@@ -11,6 +15,8 @@ import { useNuiRequest } from 'fivem-nui-react-lib';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useHistory } from 'react-router'; import { useHistory } from 'react-router';
import { CallEvents } from '../../../../../../typings/call'; import { CallEvents } from '../../../../../../typings/call';
import { fetchNui } from '../../../../utils/fetchNui';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
const useStyles = makeStyles((theme: Theme) => ({ const useStyles = makeStyles((theme: Theme) => ({
icon: { icon: {
@@ -18,21 +24,48 @@ const useStyles = makeStyles((theme: Theme) => ({
}, },
})); }));
export const ListingActions = ({ listing }: { listing: MarketplaceListing }) => { export const ListingActions: React.FC<MarketplaceListing> = ({ children, ...listing }) => {
const Nui = useNuiRequest(); const Nui = useNuiRequest();
const classes = useStyles(); const classes = useStyles();
const { number: myNumber } = useSimcard(); const { number: myNumber } = useSimcard();
const { t } = useTranslation(); const { t } = useTranslation();
const history = useHistory(); const history = useHistory();
const { addAlert } = useSnackbar();
const handleDeleteListing = () => { const handleDeleteListing = () => {
Nui.send(MarketplaceEvents.DELETE_LISTING, { fetchNui<MarketplaceActionResp>(MarketplaceEvents.DELETE_LISTING, {
id: listing.id, id: listing.id,
}).then(({ err, errMsg }) => {
if (err) {
return addAlert({
message: t(errMsg),
type: 'error',
});
}
addAlert({
message: t('APPS_MARKETPLACE_DELETE_LISTING_SUCCESS'),
type: 'success',
});
}); });
}; };
const handleReportListing = () => { const handleReportListing = () => {
Nui.send(MarketplaceEvents.REPORT_LISTING, listing); fetchNui<MarketplaceActionResp>(MarketplaceEvents.DELETE_LISTING, listing).then(
({ err, errMsg }) => {
if (err) {
return addAlert({
message: t(errMsg),
type: 'error',
});
}
addAlert({
message: t('APPS_MARKETPLACE_REPORT_LISTING_SUCCESS'),
type: 'success',
});
},
);
}; };
const handleCall = () => { const handleCall = () => {
@@ -46,9 +79,9 @@ export const ListingActions = ({ listing }: { listing: MarketplaceListing }) =>
}; };
return ( return (
<Box flex justifyContent="space-between" alignItems="center"> <Box justifyContent="space-between" alignItems="center">
<div style={{ float: 'left' }}> <div style={{ float: 'left' }}>
{listing.number !== myNumber ? ( {listing.number !== myNumber && (
<> <>
<Tooltip title={t('GENERIC_MESSAGE')}> <Tooltip title={t('GENERIC_MESSAGE')}>
<Button onClick={handleMessage}> <Button onClick={handleMessage}>
@@ -61,7 +94,7 @@ export const ListingActions = ({ listing }: { listing: MarketplaceListing }) =>
</Button> </Button>
</Tooltip> </Tooltip>
</> </>
) : null} )}
</div> </div>
<div style={{ float: 'right' }}> <div style={{ float: 'right' }}>
@@ -41,7 +41,7 @@ const useStyles = makeStyles((theme) => ({
}, },
})); }));
export const MarketplaceItem = (listing: MarketplaceListing) => { export const MarketplaceItem: React.FC<MarketplaceListing> = ({ children, ...listing }) => {
const classes = useStyles(); const classes = useStyles();
return ( return (
@@ -73,7 +73,7 @@ export const MarketplaceItem = (listing: MarketplaceListing) => {
<Typography variant="body1" className={classes.listingContent}> <Typography variant="body1" className={classes.listingContent}>
{listing.description} {listing.description}
</Typography> </Typography>
<ListingActions listing={listing} /> <ListingActions {...listing} />
</Paper> </Paper>
</div> </div>
</ListItem> </ListItem>
@@ -1,10 +1,10 @@
import React from 'react'; import React from 'react';
import { List } from '../../../../ui/components/List'; import { List } from '../../../../ui/components/List';
import { useListing } from '../../hooks/useListing'; import { useListingValue } from '../../hooks/state';
import { MarketplaceItem } from './MarketplaceItem'; import { MarketplaceItem } from './MarketplaceItem';
export const MarketplaceList = () => { export const MarketplaceList: React.FC = () => {
const listings = useListing(); const listings = useListingValue();
return ( return (
<List> <List>
@@ -0,0 +1,17 @@
import React from 'react';
import { MarketplaceList } from './MarketplaceList';
import { Box, CircularProgress } from '@material-ui/core';
const LoadingListings: React.FC = () => (
<Box display="flex" flexGrow={1} width="100%" justifyContent="center" alignItems="center">
<CircularProgress />
</Box>
);
export const MarketplaceListContainer: React.FC = () => {
return (
<React.Suspense fallback={<LoadingListings />}>
<MarketplaceList />
</React.Suspense>
);
};
@@ -1,6 +0,0 @@
import React from 'react';
import { MarketplaceList } from './MarketplaceList';
export const MarketplaceListContainer = () => {
return <MarketplaceList />;
};
@@ -1,7 +1,6 @@
import React, { useEffect, useState, useCallback } from 'react'; import React, { useEffect, useState, useCallback } from 'react';
import { makeStyles, Button, Box } from '@material-ui/core'; import { makeStyles, Button, Box } from '@material-ui/core';
import { useNuiRequest } from 'fivem-nui-react-lib'; import { MarketplaceActionResp, MarketplaceEvents } from '../../../../../../typings/marketplace';
import { MarketplaceEvents } from '../../../../../../typings/marketplace';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import ImageIcon from '@material-ui/icons/Image'; import ImageIcon from '@material-ui/icons/Image';
@@ -10,6 +9,7 @@ import qs from 'qs';
import { useQueryParams } from '../../../../common/hooks/useQueryParams'; import { useQueryParams } from '../../../../common/hooks/useQueryParams';
import { deleteQueryFromLocation } from '../../../../common/utils/deleteQueryFromLocation'; import { deleteQueryFromLocation } from '../../../../common/utils/deleteQueryFromLocation';
import { TextField } from '../../../../ui/components/Input'; import { TextField } from '../../../../ui/components/Input';
import { fetchNui } from '../../../../utils/fetchNui';
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
root: { root: {
@@ -36,7 +36,6 @@ const useStyles = makeStyles((theme) => ({
})); }));
export const ListingForm = () => { export const ListingForm = () => {
const Nui = useNuiRequest();
const classes = useStyles(); const classes = useStyles();
const { t } = useTranslation(); const { t } = useTranslation();
const { addAlert } = useSnackbar(); const { addAlert } = useSnackbar();
@@ -50,12 +49,24 @@ export const ListingForm = () => {
const addListing = () => { const addListing = () => {
if (title !== '' && description !== '') { if (title !== '' && description !== '') {
Nui.send(MarketplaceEvents.ADD_LISTING, { fetchNui<MarketplaceActionResp>(MarketplaceEvents.ADD_LISTING, {
title, title,
url,
description, description,
url,
}).then(({ err, errMsg }) => {
if (err) {
return addAlert({
message: t(errMsg),
type: 'error',
});
}
addAlert({
message: t('APPS_MARKETPLACE_CREATE_LISTING_SUCCESS'),
type: 'success',
}); });
history.push('/marketplace'); history.push('/marketplace');
});
} else { } else {
addAlert({ addAlert({
message: t('APPS_MARKETPLACE_REQUIRED_FIELDS'), message: t('APPS_MARKETPLACE_REQUIRED_FIELDS'),
+42 -7
View File
@@ -1,9 +1,44 @@
import { atom } from 'recoil'; import { atom, selector, useRecoilValue, useSetRecoilState } from 'recoil';
import { MarketplaceListing } from '../../../../../typings/marketplace'; import { MarketplaceEvents, MarketplaceListing } from '../../../../../typings/marketplace';
import { fetchNui } from '../../../utils/fetchNui';
export const selloutState = { const defaultData: MarketplaceListing[] = [
listing: atom<MarketplaceListing[]>({ {
key: 'listing', id: 1,
default: [], name: 'Some guy',
number: '111-1134',
username: 'Taso',
title: 'eeeeeeeeeeeeeeeeeeeeeeeee',
description:
'skldfsdEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE',
url: 'https://beta.iodine.gg/706Y3.jpeg',
},
{
id: 2,
name: 'Some other dude',
number: '666-6666',
username: 'Taso',
title: 'Material',
description: 'Selling my wife',
url: '',
},
];
const listingState = atom<MarketplaceListing[]>({
key: 'listings',
default: selector({
key: 'defaultListings',
get: async () => {
try {
return await fetchNui<MarketplaceListing[]>(MarketplaceEvents.FETCH_LISTING);
} catch (e) {
if (process.env.NODE_ENV === 'development' && !process.env.REACT_APP_IN_GAME) {
return defaultData;
}
}
},
}), }),
}; });
export const useListingValue = () => useRecoilValue(listingState);
export const useSetListings = () => useSetRecoilState(listingState);
@@ -1,7 +0,0 @@
import { useRecoilValue } from 'recoil';
import { MarketplaceListing } from '../../../../../typings/marketplace';
import { selloutState } from './state';
export const useListing = () => {
return useRecoilValue<MarketplaceListing[]>(selloutState.listing);
};
@@ -1,24 +1,32 @@
import { useNuiEvent } from 'fivem-nui-react-lib'; import { useNuiEvent } from 'fivem-nui-react-lib';
import { selloutState } from './state'; import {
import { useListing } from './useListing'; MarketPlaceBroadcastData,
import { useSetRecoilState } from 'recoil'; MarketplaceDeleteDTO,
import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar'; MarketplaceEvents,
import { useTranslation } from 'react-i18next'; MarketplaceListing,
import { MarketplaceEvents } from '../../../../../typings/marketplace'; } from '../../../../../typings/marketplace';
import { useSetListings } from './state';
export const useMarketplaceService = () => { export const useMarketplaceService = () => {
const setSellout = useSetRecoilState(selloutState.listing); const setListings = useSetListings();
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const handleAddAlert = ({ message, type }: IAlert) => { useNuiEvent<MarketPlaceBroadcastData>(
addAlert({ 'SELLOUT',
message: t(`APPS_${message}`), MarketplaceEvents.BROADCAST_EVENT,
type, ({ type, listing }) => {
if (type === 'ADD') {
const typeCastListing = listing as MarketplaceListing;
return setListings((curState) => [...curState, typeCastListing]);
}
if (type === 'DELETE') {
const deleteDTO = listing as MarketplaceDeleteDTO;
return setListings((currVal) => {
const arrayPos = currVal.map((item) => item.id).indexOf(deleteDTO.id);
return [...currVal].splice(arrayPos);
}); });
}; }
},
useNuiEvent('SELLOUT', MarketplaceEvents.SEND_ALERT, handleAddAlert); );
useNuiEvent('SELLOUT', MarketplaceEvents.SEND_LISTING, setSellout);
return useListing();
}; };
+39 -29
View File
@@ -1,37 +1,47 @@
import { MarketplaceEvents, MarketplaceListing } from '../../typings/marketplace'; import { MarketplaceEvents, MarketplaceListingBroadcast } from '../../typings/marketplace';
import { IAlertProps } from '../../typings/alerts'; import { RegisterNuiProxy } from './cl_utils';
import { sendMarketplaceEvent } from '../utils/messages'; import { sendMarketplaceEvent } from '../utils/messages';
onNet(MarketplaceEvents.SEND_LISTING, (listings: MarketplaceListing[]) => { // onNet(MarketplaceEvents.SEND_LISTING, (listings: MarketplaceListing[]) => {
sendMarketplaceEvent(MarketplaceEvents.SEND_LISTING, listings); // sendMarketplaceEvent(MarketplaceEvents.SEND_LISTING, listings);
// });
RegisterNuiProxy(MarketplaceEvents.FETCH_LISTING);
RegisterNuiProxy(MarketplaceEvents.ADD_LISTING);
// RegisterNuiCallbackType(MarketplaceEvents.ADD_LISTING);
// on(`__cfx_nui:${MarketplaceEvents.ADD_LISTING}`, (data: MarketplaceListing, cb: Function) => {
// emitNet(MarketplaceEvents.ADD_LISTING, data);
// cb();
// });
RegisterNuiProxy(MarketplaceEvents.DELETE_LISTING);
RegisterNuiProxy(MarketplaceEvents.REPORT_LISTING);
onNet(MarketplaceEvents.BROADCAST_EVENT, (broadcastEvent: MarketplaceListingBroadcast) => {
sendMarketplaceEvent(MarketplaceEvents.BROADCAST_EVENT, broadcastEvent);
}); });
RegisterNuiCallbackType(MarketplaceEvents.ADD_LISTING); // RegisterNuiCallbackType(MarketplaceEvents.DELETE_LISTING);
on(`__cfx_nui:${MarketplaceEvents.ADD_LISTING}`, (data: MarketplaceListing, cb: Function) => { // on(`__cfx_nui:${MarketplaceEvents.DELETE_LISTING}`, (data: MarketplaceListing, cb: Function) => {
emitNet(MarketplaceEvents.ADD_LISTING, data); // emitNet(MarketplaceEvents.DELETE_LISTING, data.id);
cb(); // cb();
}); // });
RegisterNuiCallbackType(MarketplaceEvents.DELETE_LISTING); // RegisterNuiCallbackType(MarketplaceEvents.REPORT_LISTING);
on(`__cfx_nui:${MarketplaceEvents.DELETE_LISTING}`, (data: MarketplaceListing, cb: Function) => { // on(`__cfx_nui:${MarketplaceEvents.REPORT_LISTING}`, (data: MarketplaceListing, cb: Function) => {
emitNet(MarketplaceEvents.DELETE_LISTING, data.id); // emitNet(MarketplaceEvents.REPORT_LISTING, data);
cb(); // cb();
}); // });
RegisterNuiCallbackType(MarketplaceEvents.REPORT_LISTING); // onNet(MarketplaceEvents.ADD_LISTING_SUCCESS, () => {
on(`__cfx_nui:${MarketplaceEvents.REPORT_LISTING}`, (data: MarketplaceListing, cb: Function) => { // emitNet(MarketplaceEvents.FETCH_LISTING);
emitNet(MarketplaceEvents.REPORT_LISTING, data); // });
cb();
});
onNet(MarketplaceEvents.ADD_LISTING_SUCCESS, () => { // onNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, () => {
emitNet(MarketplaceEvents.FETCH_LISTING); // emitNet(MarketplaceEvents.FETCH_LISTING);
}); // });
onNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, () => { // onNet(MarketplaceEvents.ACTION_RESULT, (alert: IAlertProps) => {
emitNet(MarketplaceEvents.FETCH_LISTING); // sendMarketplaceEvent(MarketplaceEvents.SEND_ALERT, alert);
}); // });
onNet(MarketplaceEvents.ACTION_RESULT, (alert: IAlertProps) => {
sendMarketplaceEvent(MarketplaceEvents.SEND_ALERT, alert);
});
+24 -1
View File
@@ -1,14 +1,22 @@
export interface MarketplaceListing { export interface MarketplaceListing extends MarketplaceListingBase {
id: number; id: number;
identifier?: string; identifier?: string;
username: string; username: string;
name: string; name: string;
number: string; number: string;
}
export interface MarketplaceListingBase {
title: string; title: string;
url: string; url: string;
description: string; description: string;
} }
export interface MarketplaceActionResp {
err: boolean;
errMsg?: string;
}
export enum MarketplaceEvents { export enum MarketplaceEvents {
ADD_LISTING = 'npwd:addListing', ADD_LISTING = 'npwd:addListing',
ADD_LISTING_SUCCESS = 'npwd:addListingSuccess', ADD_LISTING_SUCCESS = 'npwd:addListingSuccess',
@@ -21,4 +29,19 @@ export enum MarketplaceEvents {
REPORT_LISTING_SUCCESS = 'npwd:reportListingSuccess', REPORT_LISTING_SUCCESS = 'npwd:reportListingSuccess',
REPORT_LISTING_SUCESS = 'npwd:reportListingFailed', REPORT_LISTING_SUCESS = 'npwd:reportListingFailed',
SEND_ALERT = 'nwpd:sendListingAlert', SEND_ALERT = 'nwpd:sendListingAlert',
BROADCAST_EVENT = 'npwd:sendMarketplaceBroadcast',
} }
export interface MarketplaceDeleteDTO {
id: number;
}
export type MarketPlaceBroadcastData =
| {
type: 'ADD';
listing: MarketplaceListing;
}
| {
type: 'DELETE';
listing: MarketplaceDeleteDTO;
};