Search code examples
react-nativereduxreact-reduxcode-reuse

How to write and model a Reusable Business Logic in React Native


I have to develop 5 different mobile applications using React Native. The Business requirements behind the applications are the same and they should connect to the same RESTful api, but each one of them will have a different UI/UX to fulfill a branding requirements. What is the best practice to achieve extreme reusable business logic code for the applications.

Should I make the Redux as external node package and import it in each application, or should I merge the applications in one huge codebase and use a different nodejs script to build each one of them ?


Solution

  • My advise would be to separate business logic. As you are planning to use Redux, you can create models and services into a separate package and import it wherever you need.

    Models - define state, contain reducers and effects. Services - actual functions to call RestFul APIs.

    The Model <--> Services approach is very useful because they are not at all doing any UI stuff.

    See an example of Model and Service below:

    Model:

    import {
      addPayment
    } from '../services/paymentService'
    
    import {
      updateAge
    } from '../services/profileService'
    
    export default {
      namespace: 'myProfile',
      state: {
         age
         },
    
      reducers: {
        set: (state, {payload: details}) => {
          return ({...state, ...details})
        },
      },
      effects: {
        *getAge (action, { call, put, simplePut }) {
          const {payload: age} = action
          try {
            const res = yield call(upadteAge, age)
            const { status } = res
            if (status === 200) {
              const json = yield res.json()
              yield simplePut('set', json)
            } 
          } catch (error) {
            console.log(error)
          }
        },
      }
    

    Service:

    export function updateAge ({age}) {
      return fetch('apiurl?age=' + age, {
        method: 'POST',
        headers: {
        }
      })
    }
    

    I recently completed an application in which I have used the above approach and it worked like a charm.