Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooks and Redux Saga

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,

  • Do we still need redux if we use hooks?
  • How can we rewrite the above code using hooks?
like image 684
prajeesh Avatar asked May 07 '19 08:05

prajeesh


1 Answers

  1. "Do we still need redux if we use hooks?"

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.

  1. "How can we rewrite the above code using hooks?"

You can remake your class component Centers to function component like this:

function Centers(props) {
    useEffect(() => {
        props.getCenters();
    }, []);

    return (
        //render what you need here
    );
}
like image 127
Andrii Golubenko Avatar answered Nov 16 '22 04:11

Andrii Golubenko