Commit 88a15d89 authored by Martin Fahl's avatar Martin Fahl

fixes debouncing

parent b397e3bb
{
"name": "react-codingbrunch-inventory-frontend-inmemory",
"name": "inventory-frontend",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:4000",
......
import debounced from "../debounced"
describe("debounced", () => {
it("execute function after timeout", async () => {
const delay = 10
const mockFunction = jest.fn()
const debouncedFn = debounced(delay, mockFunction)
debouncedFn()
await new Promise ((resolve) => {
setTimeout(() => {
resolve()
}, delay + 10)
})
expect(mockFunction.mock.calls.length).toBe(1)
})
it("executes only the last function call after timeout", async () => {
const mockFunction = jest.fn()
const delay = 10
const debouncedFn = debounced(delay, mockFunction)
debouncedFn()
debouncedFn()
debouncedFn()
await new Promise ((resolve) => {
setTimeout(() => {
resolve()
}, delay + 10)
})
expect(mockFunction.mock.calls.length).toBe(1)
})
})
\ No newline at end of file
......@@ -11,4 +11,18 @@ const debounced = (delay, fn) => {
}
}
// const debounced = (delay, fn) => {
// let timerId;
// return function (...args) {
// if (timerId) {
// clearTimeout(timerId)
// }
// timerId = setTimeout(() => {
// fn(...args)
// timerId = null
// }, delay)
// }
// }
export default debounced
\ No newline at end of file
......@@ -38,7 +38,9 @@ export const deleteItem = (id) => dispatch => {
return Axios.delete("/api/items/"+id).then(dispatch(itemDeleted(id)))
}
const debouncedPUT = debounced(500, (dispatch, id, name, quantity) => Axios.put("/api/items/"+id, {id, name, quantity}).catch(dispatch(getAllItems)))
export const updateItem = (id, name, quantity) => dispatch => {
dispatch(itemUpdated(id, name, quantity))
debounced(500, Axios.put("/api/items/"+id, {id, name, quantity}).catch(dispatch(getAllItems)))
debouncedPUT(dispatch, id, name, quantity)
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment