Created
December 24, 2021 11:36
-
-
Save DominikStyp/f1cc651de0c7a9f21c3c80afb93d96cd to your computer and use it in GitHub Desktop.
React custom hook: useHttpMock() which mocks the HTTP request and returns the data from the JSON file instead of endpoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useCallback } from 'react'; | |
import mockTasks from '../mocks/tasks.json'; | |
const useHttpMock = () => { | |
const [isLoading, setIsLoading] = useState(false); | |
const [error, setError] = useState(null); | |
const sendRequest = useCallback(async (requestConfig, applyData) => { | |
setIsLoading(true); | |
setError(null); | |
await new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log("Request config", requestConfig); | |
console.log("Data fetched"); | |
resolve(); | |
}, | |
3000); | |
}); | |
if(requestConfig.method === 'POST'){ | |
applyData( | |
mockTasks.push({ text: requestConfig.body.text, name: `id_${(new Date()).getTime()}`}) | |
); | |
} else { | |
applyData(mockTasks); | |
} | |
setIsLoading(false); | |
}, []); | |
return { | |
isLoading, | |
error, | |
sendRequest, | |
}; | |
}; | |
export default useHttpMock; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from 'react'; | |
import Tasks from './components/Tasks/Tasks'; | |
import NewTask from './components/NewTask/NewTask'; | |
import useHttpMock from './hooks/use-http-mock'; | |
function App() { | |
const [tasks, setTasks] = useState([]); | |
const { isLoading, error, sendRequest: fetchTasks } = useHttpMock(); | |
useEffect(() => { | |
const transformTasks = (tasksObj) => { | |
const loadedTasks = []; | |
for (const taskKey in tasksObj) { | |
loadedTasks.push({ id: taskKey, text: tasksObj[taskKey].text }); | |
} | |
setTasks(loadedTasks); | |
}; | |
fetchTasks( | |
{ url: 'https://react-http-6b4a6.firebaseio.com/tasks.json' }, | |
transformTasks | |
); | |
}, [fetchTasks]); | |
const taskAddHandler = (task) => { | |
setTasks((prevTasks) => prevTasks.concat(task)); | |
}; | |
return ( | |
<React.Fragment> | |
<NewTask onAddTask={taskAddHandler} /> | |
<Tasks | |
items={tasks} | |
loading={isLoading} | |
error={error} | |
onFetch={fetchTasks} | |
/> | |
</React.Fragment> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment