uuid#v4 JavaScript Examples
The following examples show how to use
uuid#v4.
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: activities.helpers.js From web with GNU General Public License v3.0 | 6 votes |
createActivityFromNativeNotification = ({ title, content, timestamp }) => {
return {
id: v4(),
isRead: false,
title,
type: TYPE.NOTIFICATION,
content,
timestamp,
riskChecks: [],
riskLevel: 0
};
}
Example #2
Source File: idempotency-key.js From medusa with MIT License | 6 votes |
/**
* Creates an idempotency key for a request.
* If no idempotency key is provided in request, we will create a unique
* identifier.
* @param {object} payload - payload of request to create idempotency key for
* @return {Promise<IdempotencyKeyModel>} the created idempotency key
*/
async create(payload) {
return this.atomicPhase_(async (manager) => {
const idempotencyKeyRepo = manager.getCustomRepository(
this.idempotencyKeyRepository_
)
if (!payload.idempotency_key) {
payload.idempotency_key = v4()
}
const created = await idempotencyKeyRepo.create(payload)
const result = await idempotencyKeyRepo.save(created)
return result
})
}
Example #3
Source File: artworks.js From lnft with GNU Affero General Public License v3.0 | 6 votes |
app.post("/issue", auth, async (req, res) => {
let tries = 0;
try {
let { artwork, transactions } = req.body;
let issuance = v4();
let ids = transactions.map((t) => v4());
issue(issuance, ids, req);
let slug = kebab(artwork.title || "untitled") + "-" + ids[0].substr(0, 5);
let { address } = await getUser(req);
await wait(async () => {
if (++tries > 40) throw new Error("Issuance timed out");
if (!(issuances[issuance].i > 0)) return false;
let utxos = await lnft.url(`/address/${address}/utxo`).get().json();
return utxos.find((tx) => tx.asset === issuances[issuance].asset);
});
res.send({ id: ids[0], asset: issuances[issuance].asset, issuance, slug });
} catch (e) {
console.log(e);
res.code(500).send(e.message);
}
});
Example #4
Source File: Testimonials.js From gatsby-starter-netlify-cms with MIT License | 6 votes |
Testimonials = ({ testimonials }) => (
<div>
{testimonials.map((testimonial) => (
<article key={v4()} className="message">
<div className="message-body">
{testimonial.quote}
<br />
<cite> – {testimonial.author}</cite>
</div>
</article>
))}
</div>
)
Example #5
Source File: Login.js From connect-4-online-multiplayer with MIT License | 6 votes |
export default function Login() {
const iRef = useRef();
const setUser = useContext(DispatchUserContext);
function handleSubmit(e) {
e.preventDefault();
setUser({ id: v4(), name: iRef.current.value });
}
return (
<Container maxWidth="sm">
<Box textAlign="center" pt={4}>
<form onSubmit={handleSubmit}>
{/* <label>Name:</label> */}
<TextField
id="outlined-basic"
label="Enter your name"
variant="outlined"
inputRef={iRef}
required
/>
<Box py={4}>
<Button type="submit" variant="contained" color="primary">
Submit
</Button>
</Box>
</form>
</Box>
</Container>
);
}
Example #6
Source File: utils.js From aava.sh with MIT License | 6 votes |
genUuid = v4
Example #7
Source File: activities.helpers.js From web with GNU General Public License v3.0 | 6 votes |
createRiskCheck = nativeRiskCheck => {
const { timestamp } = nativeRiskCheck;
return {
id: v4(),
isRead: false,
title: '',
type: TYPE.RISK_CHECK,
content: '',
timestamp,
riskChecks: [createRiskCheckItem(nativeRiskCheck)],
riskLevel: 0
};
}
Example #8
Source File: activities.helpers.js From web with GNU General Public License v3.0 | 6 votes |
createActivityFromNativeExposure = ({ riskLevel, timestamp }) => {
return {
id: v4(),
isRead: false,
title: '',
type: TYPE.EXPOSURE,
content: '',
timestamp,
riskChecks: [],
riskLevel
};
}
Example #9
Source File: index.spec.js From web with GNU General Public License v3.0 | 6 votes |
createActivity = ({
title = '',
content = '',
timestamp,
type,
riskLevel = 0,
riskChecks = [],
isRead = false
}) => {
return {
id: v4(),
isRead,
title,
type,
content,
timestamp,
riskChecks,
riskLevel
};
}
Example #10
Source File: FakeDataGenerator.jsx From omatsuri with MIT License | 6 votes |
INITIAL_VALUES = {
fields: [
{ name: 'name', type: 'name', key: v4() },
{ name: 'birthday', type: 'date', key: v4() },
{ name: 'phone', type: 'phone', key: v4() },
{ name: 'zip', type: 'zip', key: v4() },
{ name: 'city', type: 'city', key: v4() },
{ name: 'email', type: 'email', key: v4() },
],
amount: 10,
type: 'default',
}
Example #11
Source File: InputForm.js From ReactJS-Projects with MIT License | 6 votes |
InputForm = ({ addTodos }) => {
const [todoString, setTodostring] = useState("")
const handleSubmit = (e) => {
e.preventDefault()
if (todoString === "") return alert("Please enter a To-do")
const todo = {
todoVal: todoString,
id: v4()
}
addTodos(todo)
setTodostring("")
}
return (
<Form onSubmit={handleSubmit}>
<FormGroup>
<InputGroup>
<Input type="text" name="todo" id="todo" placeholder="Enter To-do" value={todoString} onChange={e => setTodostring(e.target.value)} />
<InputGroupAddon addonType="prepend" >
<Button color="warning">
Add
</Button>
</InputGroupAddon>
</InputGroup>
</FormGroup>
</Form>
)
}
Example #12
Source File: GradientsGallery.jsx From omatsuri with MIT License | 6 votes |
export default function GradientsGallery({ className, handlers }) {
const handleGradientPick = (values) => {
window.scrollTo({ top: 0, behavior: 'smooth' });
handlers.setState(values.map((value) => ({ ...value, key: v4() })));
};
const items = data.map((item) => (
<GradientGalleryItem
key={item.name}
values={item.values}
name={item.name}
onEditorOpen={handleGradientPick}
className={classes.item}
/>
));
return (
<div className={cx(classes.gradientsGallery, className)}>
<SettingsLabel className={classes.title}>Gradients Gallery</SettingsLabel>
<div className={classes.items}>{items}</div>
</div>
);
}
Example #13
Source File: TodoForm.js From ReactJS-Projects with MIT License | 6 votes |
TodoForm = ({ addTodo }) => {
const [title, setTitle] = useState('')
const handleSubmit = e => {
e.preventDefault();
if (title === '') {
return alert('Empty Todo')
}
const todo = {
title,
id: v4()
}
addTodo(todo)
setTitle("")
}
return (
<Form onSubmit={handleSubmit}>
<FormGroup>
<InputGroup>
<Input
type="text"
name="todo"
id="todo"
placeholder='Enter Todo...'
value={title}
onChange={e => setTitle(e.target.value)}
/>
<Button color="secondary" onClick={handleSubmit}>Add</Button>
</InputGroup>
</FormGroup>
</Form>
)
}
Example #14
Source File: FakeDataGenerator.jsx From omatsuri with MIT License | 5 votes |
export default function FakeDataGenerator() {
useDocumentTitle('Fake data generator');
const ls = useLocalStorage({ key: '@omatsuri/fake-data-generator', delay: 1000 });
const initialValues = ls.retrieve() || INITIAL_VALUES;
const [fields, setFields] = useState(initialValues.fields);
const [amount, setAmount] = useState(initialValues.amount);
const [type, setType] = useState(initialValues.type);
const [seed, setSeed] = useState(null);
const regenerate = () => setSeed(v4());
useEffect(() => {
ls.save({ fields, amount, type });
return ls.cancel;
}, [type, amount, fields]);
const addField = () =>
setFields((current) => [...current, { name: '', type: 'name', key: v4() }]);
const removeField = (index) =>
setFields((current) => {
const cloned = [...current];
cloned.splice(index, 1);
return cloned;
});
const setFieldProp = (index, prop, value) =>
setFields((current) => {
const cloned = [...current];
cloned[index] = { ...cloned[index], [prop]: value };
return cloned;
});
return (
<div>
<Settings
type={type}
onTypeChange={setType}
amount={amount}
fields={fields}
onFieldAdd={addField}
onFieldRemove={removeField}
onFieldPropChange={setFieldProp}
onAmountChange={setAmount}
onRegenerate={regenerate}
/>
<Output fields={fields} amount={amount} type={type} seed={seed} />
</div>
);
}
Example #15
Source File: hooks.js From Learning-Redux with MIT License | 5 votes |
ColorProvider = ({ children }) => {
const initColors = localStorage.getItem("colors");
const [_colors, dispatch] = useReducer(
reducer,
initColors ? JSON.parse(initColors) : []
);
const colors = useMemo(() => _colors, [_colors]);
const addColor = useCallback((title, color) =>
dispatch({
type: "ADD_COLOR",
payload: {
id: v4(),
title,
color,
},
})
);
const removeColor = useCallback((id) => {
dispatch({
type: "REMOVE_COLOR",
payload: { id },
});
});
const rateColor = useCallback((id, rating) => {
dispatch({
type: "RATE_COLOR",
payload: { id, rating },
});
});
useEffect(() => {
localStorage.setItem("colors", JSON.stringify(colors));
}, [colors]);
return (
<ColorContext.Provider value={{ colors, addColor, rateColor, removeColor }}>
{children}
</ColorContext.Provider>
);
}
Example #16
Source File: GradientGenerator.jsx From omatsuri with MIT License | 5 votes |
INITIAL_VALUES = {
angle: 90,
type: 'linear',
values: [
{ color: '#ed6ea0', position: 10, opacity: 100, key: v4() },
{ color: '#ec8c69', position: 90, opacity: 100, key: v4() },
],
}
Example #17
Source File: GradientLine.jsx From omatsuri with MIT License | 5 votes |
export default function GradientLine({ values, handlers, className }) {
const [lineProps, setLineProps] = useState(null);
const parsedLineRect = useMemo(() => (lineProps ? JSON.parse(lineProps) : null), [lineProps]);
const gradient = `linear-gradient(to right, ${generateGradientColorValues(values)})`;
const handleColorAdd = (event) => {
const rect = event.target.getBoundingClientRect();
const clickPosition = event.clientX - rect.left;
const position = parseInt((clickPosition / rect.width) * 100, 10);
handlers.setState(
values
.concat({ color: getRandomColor(), position, opacity: 100, key: v4() })
.sort((a, b) => a.position - b.position)
);
};
const colorStops = values.map((value, index) => (
<ColorStop
key={value.key}
values={values}
value={value}
handlers={handlers}
lineRect={parsedLineRect}
index={index}
/>
));
return (
<div className={cx(classes.gradientLine, className)}>
<div className={classes.lineWrapper}>
<div
className={classes.line}
style={{ backgroundImage: gradient }}
onClick={handleColorAdd}
ref={(node) => node && setLineProps(JSON.stringify(node.getBoundingClientRect()))}
/>
</div>
{colorStops}
</div>
);
}
Example #18
Source File: ColorShadesGenerator.jsx From omatsuri with MIT License | 5 votes |
INITIAL_VALUES = {
value: [{ color: '#ffffff', key: v4() }],
saturation: -0.2,
darken: 0.1,
}
Example #19
Source File: ColorShadesGenerator.jsx From omatsuri with MIT License | 5 votes |
defaultPalette = Object.keys(oc)
.filter((key) => key !== 'white' && key !== 'black')
.map((key) => ({
key: v4(),
color: oc[key][4],
}))
Example #20
Source File: crypto.js From umami with MIT License | 5 votes |
export function uuid(...args) {
if (!args.length) return v4();
return v5(args.join(''), salt());
}
Example #21
Source File: ColorShadesGenerator.jsx From omatsuri with MIT License | 5 votes |
export default function ColorShadesGenerator() {
useDocumentTitle('Color shades generator');
const ls = useLocalStorage({ key: '@omatsuri', delay: 1000 });
const initialValues = ls.retrieve() || INITIAL_VALUES;
const [value, setValue] = useState(initialValues.value);
const [saturation, setSaturation] = useState(initialValues.saturation);
const [darken, setDarken] = useState(initialValues.darken);
const canDelete = value.length > 1;
const addColor = () => setValue((current) => [...current, { color: '#ffffff', key: v4() }]);
const setColor = (index, color) =>
setValue((current) => {
const cloned = [...current];
cloned[index] = { ...cloned[index], color };
return cloned;
});
const removeColor = (index) =>
setValue((current) => {
const cloned = [...current];
cloned.splice(index, 1);
return cloned;
});
const removeAll = () => setValue([{ color: '#ffffff', key: v4() }]);
const loadDefaultPalette = () => setValue(defaultPalette);
useEffect(() => {
ls.save({ value, saturation, darken });
return ls.cancel;
}, [value, saturation, darken]);
const colors = value.map((color, index) => (
<ColorShadesList
key={color.key}
value={color.color}
onChange={(c) => setColor(index, c)}
onDelete={() => removeColor(index)}
canDelete={canDelete}
saturation={saturation}
darken={darken}
/>
));
return (
<div>
<Settings
darken={darken}
onDarkenChange={setDarken}
saturation={saturation}
onSaturationChange={setSaturation}
onPaletteLoad={loadDefaultPalette}
onAllRemove={removeAll}
canRemove={canDelete}
/>
{colors}
<div className={classes.control}>
<Button onClick={addColor}>+ Add color</Button>
</div>
</div>
);
}
Example #22
Source File: uuid.js From peer2school with MIT License | 5 votes |
export function UUID() {
let array = []
v4(null, array)
return base32Encode(Buffer.from(array))
}
Example #23
Source File: index.spec.js From web with GNU General Public License v3.0 | 5 votes |
createNativeRiskCheck = (keys, exposures, timestamp, id = v4()) => ({ id, keys, exposures, timestamp })
Example #24
Source File: index.spec.js From web with GNU General Public License v3.0 | 5 votes |
createNativeExposures = (riskLevel, timestamp, id = v4()) => {
return {
id,
riskLevel,
timestamp
};
}
Example #25
Source File: index.spec.js From web with GNU General Public License v3.0 | 5 votes |
createNativeNotification = (title, content, timestamp, id = v4()) => {
return {
id,
title,
content,
timestamp
};
}
Example #26
Source File: TodoForm.js From ReactJS-Projects with MIT License | 5 votes |
TodoForm = () => {
const [todoString, setTodoString] = useState("");
const { dispatch } = useContext(TodoContext);
const handleSubmit = e => {
e.preventDefault();
if (todoString === "") return alert("Please enter to-do");
const todo = {
todoString,
id: v4()
};
dispatch({
type: ADD_TODO,
payload: todo
});
setTodoString("");
}
return (
<Form onSubmit={handleSubmit}>
<FormGroup>
<InputGroup>
<Input
type="text"
name="todo"
id="todo"
placeholder="Enter your to-do item"
value={todoString}
onChange={e => setTodoString(e.target.value)}
/>
<InputGroupAddon addonType="prepend">
<Button
color="warning"
>
Add
</Button>
</InputGroupAddon>
</InputGroup>
</FormGroup>
</Form>
)
}
Example #27
Source File: CanvasModel.js From kuwala with Apache License 2.0 | 4 votes |
CanvasModel = {
elements: [],
selectedElement: null,
selectedTransformationBlock: null,
newNodeInfo: {},
openDataView: false,
dataSource: [],
availableDataSource: [],
selectedDataSource: [],
canvasSelectedDataSource: [],
selectedColumnAddress: [],
selectedAddressObj: {},
dataBlocks: [],
transformationBlocks: [],
// Elements
addNode: action((state, nodeInfo) => {
const newNode = {
id: v4(),
...nodeInfo
};
state.elements.push(newNode)
}),
updateNodePayloadByDataBlock: action((state, {updatedNodeInfo, dataBlockId}) => {
const tempElement = state.elements;
const updatedElements = tempElement.map((el) => {
if (el.type !== DATA_BLOCK) return el
if (el.data.dataBlock.dataBlockId === dataBlockId) {
return {
...el,
data: updatedNodeInfo.data
}
} else {
return el
}
})
state.elements = updatedElements
}),
updateNodePayloadByTransformationBlock: action((state, {updatedNodeInfo, transformationBlockId}) => {
const tempElement = state.elements;
const updatedElements = tempElement.map((el) => {
if (el.type !== TRANSFORMATION_BLOCK) return el
if (el.data.transformationBlock.transformationBlockId === transformationBlockId) {
return {
...el,
data: updatedNodeInfo.data
}
} else {
return el
}
})
state.elements = updatedElements
}),
convertDataBlocksIntoElement: thunk(async (actions, nodeToRemove, {getState}) => {
const {dataBlocks, elements} = getState();
dataBlocks.forEach((block) => {
let dupeFlag = false;
// Check if Data block already converted into node
elements.forEach((curEl) => {
if (curEl.type !== DATA_BLOCK) return;
if (curEl.data.dataBlock.dataBlockId === block.dataBlockId) dupeFlag = true;
if (curEl.data.dataBlock.dataBlockEntityId === block.dataBlockEntityId) dupeFlag = true;
});
const nodeInfo = {
type: getNodeTypeByDataCatalogId(block.dataCatalogType),
data: {
label: getLabelByDataCatalogId(block.dataCatalogType),
dataSource: block.dataSourceDTO,
dataBlock: {...block},
},
sourcePosition: 'right',
}
if (dupeFlag) {
// If node same node exists -> Update the node info
actions.updateNodePayloadByDataBlock({updatedNodeInfo: nodeInfo, dataBlockId: block.dataBlockId})
} else {
// Else add new node
let position = {
x: -100,
y: Math.random() * window.innerHeight / 2,
};
if(nodeInfo.data.dataBlock.positionX && nodeInfo.data.dataBlock.positionY) {
position = {
x: nodeInfo.data.dataBlock.positionX,
y: nodeInfo.data.dataBlock.positionY
}
}
actions.addNode({
...nodeInfo,
position
})
}
});
}),
convertTransformationBlockIntoElement: thunk(async (actions, nodeToRemove, {getState}) => {
const {transformationBlocks, elements} = getState();
transformationBlocks.forEach((block) => {
let dupeFlag = false;
// Check if Data block already converted into node
elements.forEach((curEl) => {
if (curEl.type !== TRANSFORMATION_BLOCK) return;
if ((curEl.data.transformationBlock.transformationBlockId === block.transformationBlockId)) dupeFlag = true;
if ((curEl.data.transformationBlock.transformationBlockEntityId === block.transformationBlockEntityId)) dupeFlag = true;
});
const nodeInfo = {
type: getNodeTypeByDataCatalogId('transformation'),
data: {
label: block.transformationCatalog.name,
transformationCatalog: block.transformationCatalog,
transformationBlock: {...block},
},
sourcePosition: 'right',
targetPosition: 'left',
}
if (dupeFlag) {
// If node same node exists -> Update the node info
actions.updateNodePayloadByTransformationBlock({
updatedNodeInfo: nodeInfo,
transformationBlockId: block.transformationBlockId
})
} else {
// Else add new node
let position = {
x: -100,
y: Math.random() * window.innerHeight / 2,
};
if(nodeInfo.data.transformationBlock.positionX && nodeInfo.data.transformationBlock.positionY) {
position = {
x: nodeInfo.data.transformationBlock.positionX,
y: nodeInfo.data.transformationBlock.positionY
}
}
actions.addNode({
...nodeInfo,
position,
})
}
});
}),
removeNode: thunk((actions, nodesToRemove, {getState}) => {
actions.setElements(removeElements(nodesToRemove, getState().elements))
nodesToRemove.forEach((nodeToRemove) => {
if(nodeToRemove.type === DATA_BLOCK) {
actions.removeDataBlock(nodeToRemove.data.dataBlock.dataBlockId);
} else if(nodeToRemove.type === TRANSFORMATION_BLOCK) {
actions.removeTransformationBlock(nodeToRemove.data.transformationBlock.transformationBlockId);
} else if(nodeToRemove.type === CONNECTION_EDGE) {
actions.removeConnectedEdgeFromBlock({
source: nodeToRemove.source,
target: nodeToRemove.target,
});
}
});
actions.setSelectedElement(null)
}),
removeElementById: thunk((actions, elementId, {getState}) => {
const elementToRemove = getElementById(getState().elements, elementId);
actions.removeNode([elementToRemove]);
}),
connectNodes: thunk((actions, params, {getState}) => {
const edgeToAdd = {
...params,
animated: true,
type: CONNECTION_EDGE,
id: v4(),
}
const elements = getState().elements;
// Check if existing connections already exists
const connectionExists = getElementByConnectionEdgeParams(elements, params);
const target = getElementById(elements, params.target);
if(target && target.type === TRANSFORMATION_BLOCK ) {
if(target.data.transformationBlock.connectedSourceNodeIds.length < target.data.transformationCatalog.maxNumberOfInputBlocks && !connectionExists) {
actions.addConnectedEdgeToBlock({
source: params.source,
target: params.target
});
actions.addElement(edgeToAdd);
} else {
alert('Maximum number of connections reached!');
}
}
}),
addConnectedEdgeToBlock: thunk((actions, {source, target}, {getState}) => {
const sourceElement = getElementById(getState().elements, source);
const targetElement = getElementById(getState().elements, target);
let sourceDTO, targetDTO;
if(sourceElement.type === DATA_BLOCK) {
sourceDTO = sourceElement.data.dataBlock;
sourceDTO.connectedTargetNodeIds.push(target);
actions.updateDataBlock(sourceDTO);
} else if (sourceElement.type === TRANSFORMATION_BLOCK) {
sourceDTO = sourceElement.data.transformationBlock;
sourceDTO.connectedTargetNodeIds.push(target);
actions.updateTransformationBlock(sourceDTO);
}
if(targetElement.type === DATA_BLOCK) {
targetDTO = targetElement.data.dataBlock;
targetDTO.connectedSourceNodeIds.push(source);
actions.updateDataBlock(targetDTO);
} else if (targetElement.type === TRANSFORMATION_BLOCK) {
targetDTO = targetElement.data.transformationBlock;
targetDTO.connectedSourceNodeIds.push(source);
actions.updateTransformationBlock(targetDTO);
}
}),
removeConnectedEdgeFromBlock: thunk((actions, {source, target}, {getState}) => {
const sourceElement = getElementById(getState().elements, source);
const targetElement = getElementById(getState().elements, target);
let sourceDTO, targetDTO;
// Removing the targeted dto from source block
if(sourceElement) {
if(sourceElement.type === DATA_BLOCK) {
sourceDTO = sourceElement.data.dataBlock;
sourceDTO.connectedTargetNodeIds = sourceDTO.connectedTargetNodeIds.filter((el) => el !== target);
actions.updateDataBlock(sourceDTO);
} else if (sourceElement.type === TRANSFORMATION_BLOCK) {
sourceDTO = sourceElement.data.transformationBlock;
sourceDTO.connectedTargetNodeIds = sourceDTO.connectedTargetNodeIds.filter((el) => el !== target);
actions.updateTransformationBlock(sourceDTO);
}
}
// Removing the source dto from target block
if(targetElement) {
if(targetElement.type === DATA_BLOCK) {
targetDTO = targetElement.data.dataBlock;
targetDTO.connectedSourceNodeIds = targetDTO.connectedSourceNodeIds.filter((el) => el !== source);
actions.updateDataBlock(targetDTO);
} else if (targetElement.type === TRANSFORMATION_BLOCK) {
targetDTO = targetElement.data.transformationBlock;
targetDTO.connectedSourceNodeIds = targetDTO.connectedSourceNodeIds.filter((el) => el !== source);
actions.updateTransformationBlock(targetDTO);
}
}
}),
setElements: action((state, elements) => {
state.elements = elements
}),
addElement: action((state, elementToAdd) => {
state.elements = [...state.elements, elementToAdd]
}),
updateElementById: thunk((actions, elementToUpdate, {getState}) => {
const {elements} = getState();
const tempEl = elements.map((el) => {
if (el.id === elementToUpdate.id) {
const updatedEl = elementToUpdate
return updatedEl
} else {
return el
}
});
actions.setElements(tempEl);
}),
setSelectedElement: action((state, selectedNode) => {
state.selectedElement = selectedNode
}),
setSelectedElementByDataBlockId: action((state, selectedDataBlockId) => {
const selectedElement = state.elements.filter((el) => el.type === DATA_BLOCK && (el.data.dataBlock.dataBlockId === selectedDataBlockId));
if (!selectedElement.length) return
state.selectedElement = selectedElement[0]
}),
setSelectedElementByTransformationBlockId: action((state, selectedTransformationBlockId) => {
const selectedElement = state.elements.filter((el) => el.type === TRANSFORMATION_BLOCK && (el.data.transformationBlock.transformationBlockId === selectedTransformationBlockId));
if (!selectedElement.length) return
state.selectedElement = selectedElement[0]
}),
setNewNodeInfo: action((state, newNodeInfo) => {
state.newNodeInfo = newNodeInfo
}),
// TODO: Handle set selected transformation block on click
setSelectedTransformationBlock: action((state, selectedTransformationBlockId) => {
}),
setOpenDataView: action((state, openDataView) => {
state.openDataView = openDataView
}),
toggleDataView: action((state, dataView) => {
state.openDataView = !state.openDataView
}),
// Data Sources
addDataSource: action((state, dataSource) => {
state.dataSource = [...state.dataSource, ...dataSource]
}),
setDataSource: action((state, dataSource) => {
state.dataSource = dataSource
}),
getDataSources: thunk(async (actions, params, {getState}) => {
const result = await getDataSource();
await actions.getAvailableDataSource();
const dataCatalog = getState().availableDataSource;
const DTOs = [];
result.data.forEach((e, i) => {
const data_catalog_item_id = e.data_catalog_item_id;
const index = dataCatalog.findIndex((e, i) => {
if (e.id === data_catalog_item_id) return true
});
const dto = new DataSourceDTO({
id: e.id,
dataCatalogItemId: e.data_catalog_item_id,
connectionParameters: e.connection_parameters,
logo: dataCatalog[index].logo,
name: dataCatalog[index].name,
connected: e.connected,
});
DTOs.push(dto);
});
actions.setDataSource(DTOs)
}),
// Data Catalog
setAvailableDataSource: action((state, newAvailableSource) => {
state.availableDataSource = newAvailableSource
}),
getAvailableDataSource: thunk(async (actions) => {
const response = await getAllDataCatalogItems();
if (response.status === 200) {
const data = response.data
actions.setAvailableDataSource(data)
} else {
actions.setAvailableDataSource([])
}
}),
// Selected Data Sources
setSelectedSources: action((state, newSelectedSources) => {
state.selectedDataSource = newSelectedSources
}),
saveSelectedSources: thunk(async (actions, params, {getState}) => {
const selectedSource = getState().selectedDataSource;
if (!selectedSource.length) {
console.error("Selected source is empty")
return;
}
const idList = selectedSource.map((el) => el.id);
await saveSelectedDataCatalogItems({
item_ids: idList
});
actions.getDataSources()
}),
// Canvas Selected Data Source
addDataSourceToCanvas: action((state, selectedDataSource) => {
let dupe = false;
state.canvasSelectedDataSource.forEach((el) => {
if (el.id === selectedDataSource.id) dupe = true;
})
if (dupe) return
state.canvasSelectedDataSource = [...state.canvasSelectedDataSource, selectedDataSource]
}),
// Selected Column Address Action
addSelectedColumnAddress: action((state, {newAddress, dataBlockId}) => {
const addressArray = newAddress.split('@');
const schema = addressArray[0];
const category = addressArray[1];
const table = addressArray[2];
const column = addressArray[3];
let tempState = state.selectedAddressObj;
if (typeof tempState[dataBlockId] === 'undefined') {
tempState[dataBlockId] = {
[schema]: {
[category]: {
[table]: [column]
}
}
}
} else if (typeof tempState[dataBlockId][schema] === 'undefined') {
tempState[dataBlockId][schema] = {
[category]: {
[table]: [column]
}
}
} else if (typeof tempState[dataBlockId][schema][category] === 'undefined') {
tempState[dataBlockId][schema][category] = {
[table]: [column]
}
} else if (typeof tempState[dataBlockId][schema][category][table] === 'undefined') {
tempState[dataBlockId][schema][category][table] = [column]
} else {
if (!tempState[dataBlockId][schema][category][table].includes(column)) {
tempState[dataBlockId][schema][category][table].push(column)
state.selectedAddressObj = tempState
}
}
}),
removeSelectedColumnAddress: action((state, {addressToRemove, dataBlockId}) => {
const {schema, category, table, column} = columnAddressSplitter(addressToRemove);
let tempState = state.selectedAddressObj
try {
const newSelectedTableList = tempState[dataBlockId][schema][category][table].filter((el) => el !== column)
tempState[dataBlockId][schema][category][table] = newSelectedTableList
} catch (e) {
console.error(e)
}
state.selectedAddressObj = tempState
}),
generateStructureIfNotExists: action((state, {columnAddress, dataBlockId}) => {
const {schema, category, table} = columnAddressSplitter(columnAddress);
let tempState = state.selectedAddressObj;
if (typeof tempState[dataBlockId] === 'undefined') {
tempState[dataBlockId] = {
[schema]: {
[category]: {
[table]: []
}
}
}
} else if (typeof tempState[dataBlockId][schema] === 'undefined') {
tempState[dataBlockId][schema] = {
[category]: {
[table]: []
}
}
} else if (typeof tempState[dataBlockId][schema][category] === 'undefined') {
tempState[dataBlockId][schema][category] = {
[table]: []
}
} else if (typeof tempState[dataBlockId][schema][category][table] === 'undefined') {
tempState[dataBlockId][schema][category][table] = []
}
state.selectedAddressObj = tempState
}),
selectAllColumnAddresses: thunk((actions, {bulkAddress, dataBlockId}) => {
if (!bulkAddress || !bulkAddress.length) return
bulkAddress.forEach((address) => actions.addSelectedColumnAddress({
newAddress: address,
dataBlockId: dataBlockId
}))
}),
deselectAllColumnAddress: thunk((actions, {bulkAddress, dataBlockId}) => {
if (!bulkAddress || !bulkAddress.length) return
bulkAddress.forEach((address) => actions.removeSelectedColumnAddress({
addressToRemove: address,
dataBlockId: dataBlockId
}))
}),
insertOrRemoveSelectedColumnAddress: thunk(async (actions, {columnAddress, dataBlockId}, {getState}) => {
actions.generateStructureIfNotExists({columnAddress, dataBlockId});
const selectedAddressObj = getState().selectedAddressObj;
const {schema, category, table, column} = columnAddressSplitter(columnAddress);
if (selectedAddressObj[dataBlockId][schema][category][table].includes(column)) {
actions.removeSelectedColumnAddress({
addressToRemove: columnAddress,
dataBlockId: dataBlockId,
});
} else {
actions.addSelectedColumnAddress({
newAddress: columnAddress,
dataBlockId: dataBlockId,
});
}
}),
// Data Blocks
addDataBlock: action((state, newDataBlock) => {
state.dataBlocks = [...state.dataBlocks, newDataBlock]
}),
setDataBlocks: action((state, dataBlocks) => {
state.dataBlocks = dataBlocks;
}),
updateDataBlock: thunk((actions, updatedBlock, {getState}) => {
const {dataBlocks} = getState();
const blocks = dataBlocks.map((curEl) => {
if (curEl.dataBlockId === updatedBlock.dataBlockId) {
const updateDTO = new DataBlockDTO({...updatedBlock})
return updateDTO
} else {
return curEl
}
});
actions.setDataBlocks(blocks);
actions.convertDataBlocksIntoElement()
}),
removeDataBlock: thunk((actions, dataBlockId, {getState}) => {
const temp = getState().dataBlocks.filter((el) => el.dataBlockId !== dataBlockId);
actions.setDataBlocks(temp);
}),
// Transformation Block
addTransformationBlock: action((state, newTransformationBlock) => {
state.transformationBlocks = [...state.transformationBlocks, newTransformationBlock]
}),
setTransformationBlocks: action((state, transformationBlocks) => {
state.transformationBlocks = transformationBlocks;
}),
updateTransformationBlock: thunk((actions, updatedBlock, {getState}) => {
const {transformationBlocks} = getState();
const blocks = transformationBlocks.map((curEl) => {
if (curEl.transformationBlockId === updatedBlock.transformationBlockId) {
const updatedBlockDTO = new TransformationBlockDTO({...updatedBlock});
return updatedBlockDTO
} else {
return curEl
}
});
actions.setTransformationBlocks(blocks);
actions.convertTransformationBlockIntoElement();
}),
removeTransformationBlock: thunk((actions, transformationBlockId, {getState}) => {
const temp = getState().transformationBlocks.filter((el) => el.transformationBlockId !== transformationBlockId);
actions.setTransformationBlocks(temp);
}),
// Loader
loadConnections: thunk(async (actions, transformationBlockId, {getState}) => {
const {elements, transformationBlocks} = getState();
for (const tfBlock of transformationBlocks) {
const currentElement = getBlockByEntityId(elements, tfBlock.transformationBlockEntityId);
const connectedElements = getElementsByEntityIds(elements, tfBlock.inputBlockIds);
for (const sourceElement of connectedElements) {
const tempParams = {
source: sourceElement.id,
sourceHandle: null,
target: currentElement.id,
targetHandle: null
}
actions.connectNodes(tempParams)
}
}
}),
}
Example #28
Source File: index.spec.js From web with GNU General Public License v3.0 | 4 votes |
describe('prepare notifications activities', () => {
it('should prepare empty when all data are empty', () => {
const activities = [];
const notifications = [];
const riskChecks = [];
const exposures = [];
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([]);
});
it('should prepare empty when all data are undefined', () => {
const activities = undefined;
const notifications = undefined;
const riskChecks = undefined;
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([]);
});
it('should prepare activities when only notifications received', () => {
const notifications = [
createNativeNotification('title1', 'content1', 6789),
createNativeNotification('title2', 'content2', 12345)
];
const activities = undefined;
const riskChecks = undefined;
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: 'content2',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 12345,
title: 'title2',
type: TYPE.NOTIFICATION
},
{
content: 'content1',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 6789,
title: 'title1',
type: TYPE.NOTIFICATION
}
]);
});
it('should prepare activities when notifications exist and only notifications received', () => {
const notifications = [
createNativeNotification('title1', 'content1', 6789),
createNativeNotification('title2', 'content2', 333)
];
const activities = [
createActivity({ title: 'title3', content: 'content3', timestamp: 111, type: TYPE.NOTIFICATION }),
createActivity({ title: 'title4', content: 'content4', timestamp: 99999, type: TYPE.NOTIFICATION })
];
const riskChecks = undefined;
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: 'content4',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 99999,
title: 'title4',
type: TYPE.NOTIFICATION
},
{
content: 'content1',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 6789,
title: 'title1',
type: TYPE.NOTIFICATION
},
{
content: 'content2',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 333,
title: 'title2',
type: TYPE.NOTIFICATION
},
{
content: 'content3',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 111,
title: 'title3',
type: TYPE.NOTIFICATION
}
]);
});
it('should prepare activities when notifications exist and exposures and notifications received', () => {
const notifications = [createNativeNotification('title1', 'content1', 6789)];
const activities = [
createActivity({ title: 'title3', content: 'content3', timestamp: 111, type: TYPE.NOTIFICATION })
];
const riskChecks = undefined;
const exposures = [createNativeExposures(1, 5000)];
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: 'content1',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 6789,
title: 'title1',
type: TYPE.NOTIFICATION
},
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 1,
timestamp: 5000,
title: '',
type: TYPE.EXPOSURE
},
{
content: 'content3',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 111,
title: 'title3',
type: TYPE.NOTIFICATION
}
]);
});
it('should prepare activities when multiple risk checks received from different days', () => {
const notifications = undefined;
const activities = undefined;
const riskChecks = [createNativeRiskCheck(12, 1, 1607074907), createNativeRiskCheck(10, 3, 1606988507)];
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [{ timestamp: 1607074907, keys: 12, exposures: 1 }],
riskLevel: 0,
timestamp: 1607074907,
title: '',
type: TYPE.RISK_CHECK
},
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [{ timestamp: 1606988507, keys: 10, exposures: 3 }],
riskLevel: 0,
timestamp: 1606988507,
title: '',
type: TYPE.RISK_CHECK
}
]);
});
it('should prepare activities when multiple risk checks received from the same day', () => {
const notifications = undefined;
const activities = undefined;
const riskChecks = [createNativeRiskCheck(10, 3, 1607071307), createNativeRiskCheck(12, 1, 1607074907)];
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [
{ timestamp: 1607074907, keys: 12, exposures: 1 },
{ timestamp: 1607071307, keys: 10, exposures: 3 }
],
riskLevel: 0,
timestamp: 1607074907,
title: '',
type: TYPE.RISK_CHECK
}
]);
});
it('should prepare activities when multiple risk checks received from the same day and one different', () => {
const notifications = undefined;
const activities = undefined;
const riskChecks = [
createNativeRiskCheck(10, 3, 1607071307),
createNativeRiskCheck(100, 31, 1606981307),
createNativeRiskCheck(12, 1, 1607074907)
];
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [
{ timestamp: 1607074907, keys: 12, exposures: 1 },
{ timestamp: 1607071307, keys: 10, exposures: 3 }
],
riskLevel: 0,
timestamp: 1607074907,
title: '',
type: TYPE.RISK_CHECK
},
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [{ timestamp: 1606981307, keys: 100, exposures: 31 }],
riskLevel: 0,
timestamp: 1606981307,
title: '',
type: TYPE.RISK_CHECK
}
]);
});
it('should prepare activities when multiple risk checks received from the same day and one exists from that day and the second from another day', () => {
const notifications = undefined;
const activities = [
createActivity({
riskChecks: [{ keys: 100, exposures: 12, timestamp: 1607067707 }],
timestamp: 1607067707, // 4 December 2020
type: TYPE.RISK_CHECK
}),
createActivity({
riskChecks: [{ keys: 1000, exposures: 112, timestamp: 1606894907 }],
timestamp: 1606894907, // 2 December 2020
type: TYPE.RISK_CHECK
})
];
const riskChecks = [createNativeRiskCheck(10, 3, 1607071307), createNativeRiskCheck(12, 1, 1607074907)]; // 4 December 2020
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [
{ timestamp: 1607074907, keys: 12, exposures: 1 },
{ timestamp: 1607071307, keys: 10, exposures: 3 },
{ timestamp: 1607067707, keys: 100, exposures: 12 }
],
riskLevel: 0,
timestamp: 1607074907, // 4 December 2020
title: '',
type: TYPE.RISK_CHECK
},
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [{ timestamp: 1606894907, keys: 1000, exposures: 112 }],
riskLevel: 0,
timestamp: 1606894907, // 2 December 2020
title: '',
type: TYPE.RISK_CHECK
}
]);
});
it('should prepare activities when multiple risk checks received from different days and existing with different days', () => {
const notifications = undefined;
const activities = [
createActivity({
riskChecks: [{ keys: 1, exposures: 2, timestamp: 1607067707 }],
timestamp: 1607067707, // 4 December 2020
type: TYPE.RISK_CHECK
}),
createActivity({
riskChecks: [{ keys: 3, exposures: 4, timestamp: 1606977227 }],
timestamp: 1606977227, // 3 December 2020
type: TYPE.RISK_CHECK
}),
createActivity({
riskChecks: [
{ keys: 5, exposures: 6, timestamp: 1606894427 },
{ keys: 7, exposures: 8, timestamp: 1606890827 }
],
timestamp: 1606894427, // 2 December 2020
type: TYPE.RISK_CHECK
}),
createActivity({
riskChecks: [{ keys: 15, exposures: 16, timestamp: 1606804427 }],
timestamp: 1606804427, // 1 December 2020
type: TYPE.RISK_CHECK
})
];
const riskChecks = [
createNativeRiskCheck(9, 10, 1607071307), // 4 December 2020
createNativeRiskCheck(11, 12, 1606808507), // 1 December 2020
createNativeRiskCheck(13, 14, 1607074907), // 4 December 2020
createNativeRiskCheck(17, 18, 1606892427) // 2 December 2020
];
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [
{ timestamp: 1607074907, keys: 13, exposures: 14 },
{ timestamp: 1607071307, keys: 9, exposures: 10 },
{ timestamp: 1607067707, keys: 1, exposures: 2 }
],
riskLevel: 0,
timestamp: 1607074907, // 4 December 2020
title: '',
type: TYPE.RISK_CHECK
},
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [{ timestamp: 1606977227, keys: 3, exposures: 4 }],
riskLevel: 0,
timestamp: 1606977227, // 3 December 2020
title: '',
type: TYPE.RISK_CHECK
},
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [
{ timestamp: 1606894427, keys: 5, exposures: 6 },
{ timestamp: 1606892427, keys: 17, exposures: 18 },
{ timestamp: 1606890827, keys: 7, exposures: 8 }
],
riskLevel: 0,
timestamp: 1606894427, // 2 December 2020
title: '',
type: TYPE.RISK_CHECK
},
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [
{ timestamp: 1606808507, keys: 11, exposures: 12 },
{ timestamp: 1606804427, keys: 15, exposures: 16 }
],
riskLevel: 0,
timestamp: 1606808507, // 1 December 2020
title: '',
type: TYPE.RISK_CHECK
}
]);
});
it('should prepare activities when risk checks received but other type exists in the same day', () => {
const notifications = undefined;
const activities = [
createActivity({
timestamp: 1607060028, // 4 December 2020
type: TYPE.NOTIFICATION,
content: 'content1',
title: 'title1'
}),
createActivity({
riskChecks: [
{ keys: 1345, exposures: 0, timestamp: 1607060027 },
{ keys: 1222, exposures: 1, timestamp: 1607060026 }
],
timestamp: 1607060027, // 4 December 2020
type: TYPE.RISK_CHECK
})
];
const riskChecks = [
createNativeRiskCheck(1345, 0, 1607063626), // 4 December 2020
createNativeRiskCheck(1222, 1, 1607063627) // 4 December 2020
];
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [
{ timestamp: 1607063627, keys: 1222, exposures: 1 },
{ timestamp: 1607063626, keys: 1345, exposures: 0 },
{ timestamp: 1607060027, keys: 1345, exposures: 0 },
{ timestamp: 1607060026, keys: 1222, exposures: 1 }
],
riskLevel: 0,
timestamp: 1607063627, // 4 December 2020
title: '',
type: TYPE.RISK_CHECK
},
{
content: 'content1',
id: expect.any(String),
isRead: false,
riskChecks: [],
riskLevel: 0,
timestamp: 1607060028, // 4 December 2020
title: 'title1',
type: TYPE.NOTIFICATION
}
]);
});
it('should prepare activities when risk checks received but existing were read', () => {
const notifications = undefined;
const activities = [
createActivity({
riskChecks: [
{ keys: 1345, exposures: 0, timestamp: 1607060027 },
{ keys: 1222, exposures: 1, timestamp: 1607060026 }
],
timestamp: 1607060027, // 4 December 2020
type: TYPE.RISK_CHECK,
isRead: true
})
];
const riskChecks = [
createNativeRiskCheck(1222, 1, 1607063627) // 4 December 2020
];
const exposures = undefined;
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures);
expect(preparedActivities).toEqual([
{
content: '',
id: expect.any(String),
isRead: false,
riskChecks: [
{ timestamp: 1607063627, keys: 1222, exposures: 1 },
{ timestamp: 1607060027, keys: 1345, exposures: 0 },
{ timestamp: 1607060026, keys: 1222, exposures: 1 }
],
riskLevel: 0,
timestamp: 1607063627, // 4 December 2020
title: '',
type: TYPE.RISK_CHECK
}
]);
});
it('should skip activities when some exist', () => {
const notification1Id = v4();
const notification2Id = v4();
const riskCheckId = v4();
const exposureId = v4();
const fetchedIds = {
notifications: [notification1Id, notification2Id],
riskChecks: [riskCheckId],
exposures: [exposureId]
};
const notifications = [
createNativeNotification('title1', 'content1', 6789, notification1Id),
createNativeNotification('title2', 'content2', 333, notification2Id)
];
const activities = [];
const riskChecks = [
createNativeRiskCheck(1222, 1, 1607063627, riskCheckId) // 4 December 2020
];
const exposures = [createNativeExposures(1, 5000, exposureId)];
const preparedActivities = prepareActivities(activities, notifications, riskChecks, exposures, fetchedIds);
expect(preparedActivities).toEqual([]);
});
});
Example #29
Source File: AddContact.js From ReactJS-Projects with MIT License | 4 votes |
AddContact = () => {
const { state, dispatch } = useContext(ContactContext)
const { contactToUpdate, contactToUpdateKey } = state
const history = useHistory()
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [phoneNumber, setPhoneNumber] = useState("")
const [address, setAddress] = useState("")
const [isUploading, setIsUploading] = useState(false)
const [downloadUrl, setDownloadUrl] = useState(null)
const [star, setStar] = useState(false)
const [isUpdate, setIsUpdate] = useState(false)
useEffect(() => {
if (contactToUpdate) {
setName(contactToUpdate.name)
setEmail(contactToUpdate.email)
setPhoneNumber(contactToUpdate.phoneNumber)
setAddress(contactToUpdate.address)
setStar(contactToUpdate.star)
setDownloadUrl(contactToUpdate.picture)
setIsUpdate(true)
}
}, [contactToUpdate])
const imagePicker = async e => {
try {
const file = e.target.files[0]
var metadata = {
contentType: file.type
}
let resizedImage = await readAndCompressImage(file, imageConfig)
const storageRef = await firebase.storage().ref()
var upload = storageRef.child('iamges/' + file.name).put(resizedImage, metadata)
upload.on(
firebase.storage.TaskEvent.STATE_CHANGED,
snapshot => {
setIsUploading(true)
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
setIsUploading(false)
console.log('Uploading Paused.')
break;
case firebase.storage.TaskState.RUNNING:
console.log('Uploading In Progress.')
break;
case firebase.storage.TaskState.FAILED:
setIsUploading(false)
console.log('Uploading Failed.')
break;
case firebase.storage.TaskState.SUCCESS:
console.log('Uploading Successful.')
break;
}
if (progress == 100) {
setIsUploading(false);
toast("Uploaded!", { type: "success" })
}
},
error => {
toast('Something went wrong.', { type: 'error' })
}, () => {
upload.snapshot.ref.getDownloadURL().then(downloadUrl => {
setDownloadUrl(downloadUrl)
}).catch(err => console.log(err))
}
)
} catch (err) {
console.log(err)
toast('Something went wrong', { type: "error" })
}
}
const addContact = async () => {
try {
firebase.database().ref('contacts/' + v4()).set({
name,
email,
phoneNumber,
address,
picture: downloadUrl,
star
})
} catch (err) {
console.log(err)
}
}
const updateContact = async () => {
try {
firebase.database().ref('contacts/' + contactToUpdateKey).set(
{
name,
email,
phoneNumber,
address,
picture: downloadUrl,
star
}
)
} catch (err) {
console.log(err)
toast('Failed to update', { type: 'error' })
}
}
const handleSubmit = e => {
e.preventDefault()
isUpdate ? updateContact() : addContact()
toast('Success', { type: 'success' })
dispatch({
type: CONTACT_TO_UPDATE,
payload: null,
key: null
})
history.push("/")
}
return (
<Container fluid className="mt-5">
<Row>
<Col md="6" className="offset-md-3 p-2">
<Form onSubmit={handleSubmit}>
<div className="text-center">
{isUploading ? (
<Spinner type="grow" color="primary" />
) : (
<div>
<label htmlFor="imagepicker" className="">
<img src={downloadUrl} alt="" className="profile" />
</label>
<input
type="file"
name="image"
id="imagepicker"
accept="image/*"
multiple={false}
onChange={e => imagePicker(e)}
className="hidden"
/>
</div>
)}
</div>
<FormGroup>
<Input
type="text"
name="name"
id="name"
placeholder="Name"
value={name}
onChange={e => setName(e.target.value)}
/>
</FormGroup>
<FormGroup>
<Input
type="email"
name="email"
id="email"
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="Email"
/>
</FormGroup>
<FormGroup>
<Input
type="number"
name="number"
id="phonenumber"
value={phoneNumber}
onChange={e => setPhoneNumber(e.target.value)}
placeholder="phone number"
/>
</FormGroup>
<FormGroup>
<Input
type="textarea"
name="area"
id="area"
value={address}
onChange={e => setAddress(e.target.value)}
placeholder="address"
/>
</FormGroup>
<FormGroup check>
<Label check>
<Input
type="checkbox"
onChange={() => {
setStar(!star)
}}
checked={star}
/>{" "}
<span className="text-right">Mark as Star</span>
</Label>
</FormGroup>
<Button
type="submit"
color="primary"
block
className="text-uppercase"
>
{isUpdate ? "Update Contact" : "Add Contact"}
</Button>
</Form>
</Col>
</Row>
</Container>
)
}