Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure an object to retrieve the return value from a method?

I was working with immutability and redux and I am facing a problem which isn't grave but if there is a solution for it, then that would be great. Answer might be silly but since I am new to ES, I am thinking how can we achieve it.

Below is my reducer:

import Immutable from 'immutable';
import { TODOYO } from '../constants/action-types';

const initialState = Immutable.Map({
  message: null,
});

export default function todos(state = initialState, action) {
  switch (action.type) {
    case TODOYO:
      return state.set('message', action.payload);
    default:
      return state;
  }
}

Below is my mapStateToProps function in a component:

function mapStateToProps(state) {
  const message = state.todos.get('message');

  return {
    message,
  };
}

How can I destructure state to retrieve the message?

I was thinking something like this:

const {
  todos: {
    message: get('message')
  }
} = state;

which is wrong. Is there a way to retrieve message?

like image 923
shet_tayyy Avatar asked Sep 17 '25 09:09

shet_tayyy


1 Answers

If you don't have message as one of the keys of your state, you can do this using the default parameters syntax. If message does exist as a property on your state, the default will be overridden. So use with caution.

function mapStateToProps({ todos, message = todos.get('message') }) {
  return {
    message,
  };
}

And you can also shorten mapStateToProps to an arrow function:

const mapStateToProps = ({ todos, message = todos.get('message') }) => ({
  message
});
like image 107
Ori Drori Avatar answered Sep 18 '25 23:09

Ori Drori