The structure of the state object in reduction

What is the best practice for structuring a state object in Redux with respect to related objects.

Example:

User has one Organisation

With the above diagram, where we also have a list of organizations, the following example is a good idea?

{
    user: {
        id: 1,
        organisation_id: 3,
        first_name: 'Andrew',
        last_name: 'McLagan',
        email: 'andrew@example.com',
        organisation: {
            name: 'Foo Bar Co.'
            suburb: 'Booklyn',
            phone: '123-123-000',
        },
    },
    orgnaisations: [
        {
            id: 1,
            name: 'Facebook'
            suburb: 'Booklyn',
            phone: '000-000-000',
        },
        {
            id: 2,
            name: 'Twitter'
            suburb: 'Manhattan',
            phone: '456-456-000',
        },
        {
            id: 3,
            name: 'Foo Bar Co.'
            suburb: 'Booklyn',
            phone: '123-123-000',
        },
        {
            id: 4,
            name: 'Some Org.'
            suburb: 'Bronx',
            phone: '642-642-000',
        },                      
    ]
}   

Or it would be better to access a user organization:

const organisation = state.organisations[user.organisation_id];
+4
source share
1 answer

I think it’s better to access user organizations through their identifier. Here is a possible way to organize your condition:

{
  user: {
    id: 1,
    first_name: 'Andrew',
    last_name: 'McLagan',
    email: 'andrew@example.com',
    organization: 3,
  },
  organizations: {
    1: {id: 1, name: 'Facebook', suburb: 'Booklyn', phone: '000-000-000',},
    2: {id: 2, name: 'Twitter', suburb: 'Manhattan', phone: '456-456-000'},
    3: {id: 3, name: 'Foo Bar Co.', suburb: 'Booklyn', phone: '123-123-000'},
    4: {id: 4, name: 'Some Org.', suburb: 'Bronx', phone: '642-642-000'},
  }
}

Using vanilla Redux

If you want to get the current user and his organization, you can use the following selector:

function mapStateToProps(state) {
  return {
    user: state.user,
    organization: state.organizations[state.user.organization]
  }
}

. :

function mapStateToProps(state) {
  return {
    organizations: Object.values(state.organizations),
  }
}

, reselect . :

// Get a list of all organizations
const getAllOrganizations = createSelector(
  state => state.organizations,
  orgs => Object.values(orgs)
)

// Get the current user
const getUser = state => state.user

// Get the current user organization
const getUserOrganization = createSelector(
  [
    state => state.user,
    state => state.organizations,
  ],
  (user, orgs) => orgs[user.organization],
)

mapStateToProps. :

// Get the current user and his organization
function mapStateToProps(state) {
  return {
    user: getUser(state),
    organization: getUserOrganization(state),
  }
}

// Get all organizations
const mapStateToProps = getAllOrganizations
+1

All Articles