0

I'm trying to build a hook which would return a selected subset of key-value pairs from an object. Assuming that the hook has access to an object which looks like this:

const stores = { someStore: { someField: 'fieldValue' } }

how can we pass a callback to a hook to select fields from the stores object? The ideal scenario would be to have the hook work like this:

const {selectedField} = useStores(stores => ({ selectedField: stores.someStore.someField }))

The goal of this hook would be to replace MobX @inject(stores => ({...})) in my codebase.

Jakša Mališić
  • 345
  • 7
  • 13

1 Answers1

1

Just run the selector against the stores

function useStores(selector) {
  const stores = { someStore: { someField: 'fieldValue' } };
  
  return selector(stores); 
}

const { selectedField } = useStores(stores => ({ selectedField: stores.someStore.someField }));

console.log(selectedField);
Shlang
  • 2,495
  • 16
  • 24