easy-peasy computed does not take inputs

144 Views Asked by At

The Redux library easy-peasy has a function called computed which is an alternative to standard Redux selectors:

import { computed } from 'easy-peasy'

const model = {
  session: {
    totalPrice: computed(state => state.price + state.tax)
  }
}

And then the selector is called in the component like this:

import { useStoreState } from 'easy-peasy'

function TotalPriceOfProducts() {
  const totalPrice = useStoreState(state => state.products.totalPrice)
  return <div>Total: {totalPrice}</div>
}

The problem is that there doesn't seem to be a way to pass inputs to the selector. If I need a specific object in an array in the state, I can't pass the ID of the object as an input. My only option is to do this on the component side. Redux selectors have the advantage of being functions, so I can pass inputs to be used in the selector logic.

Anyone use easy-peasy come across this problem before?

1

There are 1 best solutions below

0
On

I can't pass the ID of the object as an input

To enable this, you have to return a function as your computed property.

Here is an example, exposing a computed function getTodoById:

import { computed } from 'easy-peasy'

const model = {
  todos: [],
  getTodoById: computed(state => {
    // Note how we are returning a function instead of state
    //      
    return (id) => state.todos.find(t => t.id === id)
  })
}

Then you can use it like this:

import { useStoreState } from 'easy-peasy'

function Todo({ id }) {
  const getTodoById = useStoreState(state => state.getTodoById)
  const matchingTodo = getTodoById(id);
  // ... etc
}