Skip to content

How to return Model instance from Selector instead of ref? #887

Open

Description

@alessandro308

I'm new about this library and I'm trying to understand some basic concept/use cases.

The idea I made about this library is the ability to define a Model that can have custom method to collect the logic related to the data inside a single place.

Let's suppose I have a model of a book (the same that is in the README, reported below for clarity):

class Book extends Model {
    toString() {
        return `Book: ${this.name}`;
    }
    // Declare any static or instance methods you need.
}
Book.modelName = 'Book';

// Declare your related fields.
Book.fields = {
    id: attr(), // non-relational field for any value; optional but highly recommended
    name: attr(),
};

export default Book;

in my idea, in the component, I want to make something:

const bookSelector = createSelector(orm.Book);
function MyBookComponent({bookId}){
   const book = useSelector(state => bookSelector(state, bookId))
   return book.toString();
}

but this doesn't work because the bookSelector returns the ref of the book and not the instance model.

I've seen this is explicitly made at https://github.com/redux-orm/redux-orm/blob/master/src/selectors/FieldSelectorSpec.js#L29

Is there any use case that I miss / some simplification I can do, to access the model instance using that selector?

The solution I've found now is to use

const bookSelector = createSelector(
   orm, 
  (state, bookId) => bookId, 
  (session, bookId) => return session.Book.withId(bookId),
);

but this approach looks like a bit verbose. Is it my use case a not so common usecase?

Activity

  1. alessandro308 commented on Jul 18, 2022

    @alessandro308
    Author

    I proposed a solution here: #889

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions