react - usearray() custom hook example

JSX
[Edit]
+
0
-
0

React - useArray() custom hook example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
import React, { useState, useMemo } from 'react'; // ---------------------- // Read more here: https://dirask.com/snippets/jmJNN1 // const useProxy = (action) => { const state = useMemo( () => ({ wrapper: (...args) => { if (state.action) { return state.action(...args); } return undefined; } }), [] ); state.action = action; return state.wrapper; }; // ---------------------- // Read more here: https://dirask.com/snippets/D7XEop const prependItem = (updater, item) => { updater(array => [].concat(item, array)); }; const appendItem = (updater, item) => { updater(array => [].concat(array, item)); }; const replaceItem = (updater, index, item) => { updater(array => array.map((value, i) => i === index ? item : value)); }; const removeItem = (updater, index) => { updater(array => array.filter((value, i) => i !== index)); }; // ---------------------- const useArray = (initialArray = []) => { const [items, setItems] = useState(initialArray); return { getItems: useProxy(() => items), setItems: useProxy((items) => setItems(items)), prependItem: useProxy((item) => prependItem(setItems, item)), appendItem: useProxy((item) => appendItem(setItems, item)), replaceItem: useProxy((index, item) => replaceItem(setItems, index, item)), removeItem: useProxy((index, item) => removeItem(setItems, index)), isEmpty: useProxy(() => items.length === 0), }; }; // ---------------------- // Usage example: let counter = 0; const App = () => { const array = useArray([]); const handlePrependClick = () => array.prependItem((++counter) + '-prepended'); const handleAppendedClick = () => array.appendItem((++counter) + '-appended '); const items = array.getItems(); return ( <div> <div> <button onClick={handlePrependClick}>Prepend</button> </div> <br /> <pre style={{border: '1px solid silver'}}> {items.map((item, index) => { const handleReplaceClick = () => array.replaceItem(index, (++counter) + '-replaced '); const handleRemoveClick = () => array.removeItem(index); return ( <div key={item}> <span>{item}</span> {' '} <button onClick={handleReplaceClick}>Replace</button> <button onClick={handleRemoveClick}>Remove</button> </div> ); })} </pre> <br /> <div> <button onClick={handleAppendedClick}>Append</button> </div> </div > ); }; export default App;
Reset