Search code examples
javascriptreactjsreduxreact-hooksredux-saga

How can I use custom hooks functions in saga files?


I am having trouble in using the customHooks with my redux saga here. I am new with the redux saga so couldn't able to get my head around calling the custom hooks function here.

I have created a custom hook for calling my api functions in which there is a function userLogin . Now I want this same function in to be called in the saga file, every time a particular dispatch action occurs.

What is the correct way to approach this. Should I not define my api's function inside a custom hooks ?

useApi.js

//useApi custom hook
export const useApi = () => {

    const api = useAxios();

    const userLogin = async (body, config = {}) => {
        const res = await api.post(LOGIN, body, config);
        return res.data;
    };

    return {
        userLogin,
    };
}

userSaga.js

import { takeEvery } from 'redux-saga/effects';


export function* userLoginFunction() {
    //how can I call my custom hook function here ?
    //because according to hooks rules, I cann't use the hook here.
    
    try {
       
    } catch (e) {
        
    }
}
export default function* rootSaga() {
    yield takeEvery('USER_LOGIN', fetchNumberSaga);
}

Solution

  • You can't. React hooks can be used only inside React functional components.

    But no worries 🙌.

    Instead, you can create plain API functions and use them.

    Example:

    api.js

    export const api = axios.create({ baseURL: 'https://your-api.com/api/v1' })
    

    user-api.js

    import { api } from './api'
    
    export const signIn = async ({ credentials }) => {
      const { data: user } = await api.request({
        method: 'POST',
        url: '/sign-in',
        // ... other params
      })
    
      return user
    }
    

    userSaga.js

    import { takeEvery, call } from 'redux-saga/effects';
    import { signIn } from './user-api';
    
    export function* userSignInWorker(action) {
      try {
        const user = yield call(signIn, { credentials: action.payload })
        // ... your code
      } catch (e) {
        // ... error handling
      }
    }
    
    export default function* rootSaga() {
      yield takeEvery('USER_LOGIN', userSignInWorker)
    }