I am learning redux hooks and wondering how to use it along with redux saga.
Currently the code written in saga is as follows.
centers.js
componentDidMount() {
this.props.getCenters();
}
...
<tbody>
{
this.props.centers ?
<React.Fragment>
{
centers.map((center, index) =>
<tr key={index}>
<td>{center.name}</td>
<td>{center.zip}</td>
</tr>
)
}
</React.Fragment>
:
<tr>
<td> No data available</td>
</tr>
}
</tbody>
The actions file is defined as follows.
export const getCenters = () => ({
type: types.CENTERS_REQUEST,
});
The saga file is defined as follows.
import { DEFAULT_ERROR_MSG } from '../../constants';
import { instance as centerProvider } from '../services/centerProvider';
function* fetchCenters() {
try {
const response = yield call(centerProvider.getCenters);
const centers = response.data.data.centers;
// dispatch a success action to the store
yield put({ type: types.CENTERS_SUCCESS, centers});
} catch (error) {
// dispatch a failure action to the store with the error
yield put(DEFAULT_ERROR_MSG);
}
}
export function* watchCenterRequest() {
yield takeLatest(types.CENTERS_REQUEST, fetchCenters);
}
export default function* centerSaga() {
yield all([
watchCenterRequest()
]);
}
So the question is,
You can use useReducer
hook instead of redux if you want. But if you have a shared state between different components that are deep nested in different branches of DOM tree, implementation with useReducer
could be a little bit complicated. So using redux and saga does not contradict with hooks. Hooks just needed if prefer functional components over class components.
You can remake your class component Centers
to function component like this:
function Centers(props) {
useEffect(() => {
props.getCenters();
}, []);
return (
//render what you need here
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With