How to handle/chain synchronous side effects that depend on another with React hooks
Hooks wont replace the way you handle async actions, they are just an abstraction to some things you were used to do, like calling componentDidMount
, or handling state
, etc.
In the example you are giving, you don't really need a custom hook:
function App() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const job = await import("./job.json");
const collegues = await import("./collegues.json");
const person = await import("./person.json");
setData({
job,
collegues,
person
})
};
fetchData()
}, []);
return <div className="App">{JSON.stringify(data)}</div>;
}
That being said, maybe if you provide an example of an actual redux-saga or thunks code you have, that you want to refactor, we can see what the steps are to accomplish that.
Edit:
That being said if you still want to do something like this, you can take a look at this:
https://github.com/dai-shi/react-hooks-async
import React from 'react';
import { useFetch } from 'react-hooks-async/dist/use-async-task-fetch';
const UserInfo = ({ id }) => {
const url = `https://reqres.in/api/users/${id}?delay=1`;
const { pending, error, result, abort } = useFetch(url);
if (pending) return <div>Loading...<button onClick={abort}>Abort</button></div>;
if (error) return <div>Error:{error.name}{' '}{error.message}</div>;
if (!result) return <div>No result</div>;
return <div>First Name:{result.data.first_name}</div>;
};
const App = () => (
<div>
<UserInfo id={'1'} />
<UserInfo id={'2'} />
</div>
);
EDIT
This is an interesting approach https://swr.now.sh/#dependent-fetching