Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put utility functions in a React-Redux application?

In a React-Redux application, I've got a state like this:

state = {
    items: [
        { id: 1, first_name: "John", last_name: "Smith", country: "us" },
        { id: 2, first_name: "Jinping", last_name: "Xi", country: "cn" },
    ]
}

which I render using a React component.

Now I need a function that gives me the "full name" of a person. So it's not just "first_name + last_name" but it depends on the country (for example, it would be "last_name + first_name" in China), so there's some relatively complex logic, which I would like to wrap in a function usable from any React component.

In OOP I would create a Person::getFullName() method that would give me this information. However the state object is a "dumb" one where sub-objects don't have any specialized methods.

So what is the recommended way to manage this in React-Redux in general? All I can think of is create a global function such as user_getFullName(user) which would take a user and return the full name, but that's not very elegant. Any suggestion?

like image 832
laurent Avatar asked Nov 29 '16 16:11

laurent


People also ask

How do I link a functional component to Redux?

The connect() function connects a React component to a Redux store. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.

Can you use Redux with functional components?

From there, you may import any of the listed React Redux hooks APIs and use them within your function components.


2 Answers

I follow the approach of creating libraries for cases like this in my applications, and so far this works pretty well for me.

In this case, I would create a new module, e.g. {ComponentRoot}/lib/user.js which exports a function getFullName(user) or possibly getFullName(firstName, lastName, country), depending the circumstances.

Now it is just a matter of importing the module where you require the functionality, no global functions needed:

import React from 'react'
import {getFullName} from '../lib/user'

const Title = ({user}) =>
    <div>
        {getFullName(user)}
    </div>

We place our library folder on the same level as the components folder etc., but whatever works best for you should do.

like image 167
TimoStaudinger Avatar answered Oct 14 '22 05:10

TimoStaudinger


First of all, Redux has no opinion on the file structure of your application. Some famous boilerplate projects put the code into a utils/ folder:

  • react-boilerplate
  • react-redux-universal-hot-example
  • react-slingshot
  • electron-react-boilerplate

Sample folder structure:

src/
  components/
    ...
  reducers/
    ...
  utils/
    ...
like image 29
Tyler Liu Avatar answered Oct 14 '22 07:10

Tyler Liu