0

I'm trying to use Redux selectors to extract specific data from nested data structures returned from the Redux store.

const getContactPhone = state => (state.home.data.blocks[1].contactPhone);

I'm getting this data from an API and storing it in the store when my Next.js site loads using getInitialProps. It seems that the store data appears and disappears -- perhaps this has something to do with the way Next.js and next-redux-wrapper handle store creation. In any case I kept getting 'cannot read contactPhone of undefined' errors, for example.

Obviously I can put checks in such as

const getContactPhone = state => (state && state.home && state.home.data 
 && state.home.data.blocks && state.home.data.blocks[1] ? state.home.data.blocks[1].contactPhone : '');

But that seems awkward and ugly. Is there a better way to handle this? Is there some library that will help me?

Thanks for any clues on the way forward!

Cerulean
  • 5,543
  • 9
  • 59
  • 111

1 Answers1

1

Ramda has a path function. You pass the path to the property as an array of strings. If the property exists, its value is returned; otherwise it returns undefined.

console.log(R.path(['a', 'b', 'c', 0], { a: { b: { c: [1, 2] } } })); // 1
console.log(R.path(['a', 'b', 'c', 0], {})); // undefined
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177