mapStateToProps Getting a specific piece of state

Was thinking about posting this or not, but figured someone might benefit from something I stumbled upon recently that I did not even know you could do with a mapStateToProps function in a react redux app. Not sure what category to post this.

So this is the example from my current project

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';

export class ShowAccountBook extends Component {
  /* some implementation here */ 
}

function mapStateToProps({ user }, ownProps) {
  const accountBook = accountBooks.find(
    item => item.title === ownProps.match.params.title
  );

  if (accountBook) {
    return { accounts: accountBook.accounts };
  }

  return { accounts: [] };
}

export const ConnectedShowAccountBook = connect(
  mapStateToProps
)(
  ShowAccountBook
);

This was actually written in typescript is partly why I became aware of ownProps, but I have removed all the types to make it a bit less confusing.

So what is this code doing? Well, it is using ownProps which is the properties pass to your component, not by the mapStateToProps function, in this case, React Router to figure out which exact account book I want to show and grab only the accounts for that account book from the state, I already have the title which is being passed from the parent.

For one I’ve always, and the way I’ve seen many tutorials I’ve looked at do it, is return a chunk of the state, but I’ve never really seen an example of using mapStateToProps to conditionally grab a piece of state and return that before.

So in the future when using mapStateToProps I think I’m going to have to more carefully think about how I’m doing it.

Another example I threw together was in a fairly simple ToDo app.

Anyways I hope this becomes helpful to someone.