MCPcopy
hub / github.com/epicweb-dev/react-hooks / App

Function App

exercises/02.side-effects/02.problem.cleanup/index.tsx:11–93  Β·  view source on GitHub β†—
()

Source from the content-addressed store, hash-verified

9}
10
11function App() {
12 const [query, setQuery] = useState(getQueryParam)
13
14 const words = query.split(' ')
15
16 const dogChecked = words.includes('dog')
17 const catChecked = words.includes('cat')
18 const caterpillarChecked = words.includes('caterpillar')
19
20 useEffect(() => {
21 // 🚨 we use this to test whether your cleanup is working
22 const hugeData = new Array(1_000_000).fill(
23 new Array(1_000_000).fill('πŸΆπŸ±πŸ›'),
24 )
25
26 // 🐨 extract your event handler here into a function called updateQuery
27 window.addEventListener('popstate', () => {
28 // 🚨 this console.log forces the hugeData to hang around as long as the event listener is active
29 console.log(hugeData)
30
31 console.log('popstate event listener called')
32 setQuery(getQueryParam())
33 })
34 // 🐨 return a function which removes the popstate event listener
35 // πŸ“œ https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
36 }, [])
37
38 function handleCheck(tag: string, checked: boolean) {
39 const newWords = checked ? [...words, tag] : words.filter((w) => w !== tag)
40 setQuery(newWords.filter(Boolean).join(' ').trim())
41 }
42
43 return (
44 <div className="app">
45 <form
46 action={() => {
47 setGlobalSearchParams({ query })
48 }}
49 >
50 <div>
51 <label htmlFor="searchInput">Search:</label>
52 <input
53 id="searchInput"
54 name="query"
55 type="search"
56 value={query}
57 onChange={(e) => setQuery(e.currentTarget.value)}
58 />
59 </div>
60 <div>
61 <label>
62 <input
63 type="checkbox"
64 checked={dogChecked}
65 onChange={(e) => handleCheck('dog', e.currentTarget.checked)}
66 />{' '}
67 🐢 dog
68 </label>

Callers

nothing calls this directly

Calls 3

setGlobalSearchParamsFunction Β· 0.90
getQueryParamFunction Β· 0.70
handleCheckFunction Β· 0.70

Tested by

no test coverage detected