Communicate with Redux & Redux-Saga

Communicate with Redux & Redux-Saga

ยท

7 min read

Greetings Reader,

This blog will discover the process of communication with redux store in React

Every developer maintain code in a different approach

My approach: Folder structure ๐Ÿ“‚ for this tree folders are common like - models, services, pages

1. Models

const customerModel = {
  namespace: 'customer',
};

export default customerModel;

Providing namespace will be unique all over the store and easy to remember and call its effects & reducers.

let's create a state of the customer model -

const customerModel = {
  namespace: 'customer',
  state:{
    customerList: [],
    singleCustomer: {},
  }
};

in the above state, the object will handle the response from Rest API also updates from customer components if any change happens.

let's understand how to connect with Rest API and push the response in the customerList array. for this will create a effects object which will contain the generator functions. read more about generator


redux-saga provides some helper effects wrapping internal functions to spawn tasks when some specific actions are dispatched to the Store.

effects -

  effects: {
    // * indicate its generator fun
    *setState({ payload }, { put }) {
      if (payload) {
        yield put({
          type: 'save',
          payload,
        });
      }
    },

setState is very common fun for calling multiple occurrences like user action, updating a value in the state, etc. we got two params -

  • { payload } - whatever value you would like to update in the state.
  • { put } - is a special helper function of redux-saga. It takes two params - 1. type name of reducer (save), 2. payload which needs to update in-store, payload we will understand in the component section. read more about helper
  • yield - will return the call of put which is connecting to the reducers save. The save function we will declare in the below code in the section of the reducer object.

reducers -

 reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload
      };
    },
  },

in the reducers function, you can put the logic to maintain the state of the application but currently, we are just taking the previous state of it and merging with the new state if any changes.

But in the top, we were about to get the response of customer list in put inside the customerList array

example: - Let's create a generator function & define logic as in setState fun.

*getCustomers({ payload }, { call, put }) {
      try {
        // api call -
        const response = yield call(customerListAPI, payload); 
        if (response.success) {
         // customerList key specified to store only in that array value. 
          yield put({
            type: 'save',
            payload: {
               customerList: response.data,
            }, 
          });
        }
      } catch (error) {
        console.error('error in customer list api', error);
      }
},

Explain - we wrapped the API call because we calling the promise function with the help of the call effect.

  • call -required two params - i) callback function, ii) payload - if we need any required data to be passed to the callback function, in simple word API requirement likes customer id, etc.
  • yield has control over the sequence in getting a response from API call.
  • try-catch helps the control of the function of we get any error in resolving the promise the catch will prompt us in the console.

2. Services

The services folder will contain the related API functions & common required key values.


import { Access, Secret, ApiURL } from '@/utils/env';
import request from 'umi-request'; 
// axios also can be used here if you are comfirtable with `umi-request`

const headers = {
  'Content-Type': 'application/json',
  'access': Access,
  'secret': Secret,
};

export async function customerListAPI(params) {
  return request(`${ApiURL}/v1/getcustomerlist`, {
    headers,
    method: 'GET',
  });
}

// other async functions ....
export async function customerByID(params) {
 ....
 ....
 ...
}

3. Page or components

Now the finally we have to call the model to get the data from API. What is UMI and understand how to connect works check out my article


import { connect } from 'umi';

const CustomerList = (props) => {
  const { dispatch, customer } = props;
  const { customerList } = customer;
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'customer/getCustomers',
        payload: {
          size: 10,
          page: 1,
        },
      });
    }
  }, []);

  return (
    <CommonTable
      source={ customerList }
    >
    ....
    </CommonTable>
  );
};
// to connec with redux store
export default connect(({ customer }) => ({
  customer,
}))(CustomerList);

Congratulation you made it. ๐Ÿ†

I hope you enjoyed, learned, and remember...๐Ÿ™Œ

If you liked it please leave some ๐Ÿ’™ & ๐Ÿ‘ to show your support. Also, leave your responses below and reach out to me if you face any issues.

You can find me on Twitter rkumar1904 & Hashnode Rajesh Prajapati

ThankYou.