-1

Is there a way I can destructure my data in my function arguments?

const AgendaItem = ({ item }) => {
  const { venue, organiser, startTime, endTime, description } = item;
  return (
    <View>
      <Text>Location: {venue}</Text>
      <Text>Consultant: {organiser}</Text>
      <Text>Time: {`${startTime} - ${endTime}`}</Text>
      <Text>Description: {description || "None"}</Text>
      <Text>Description: {description || "None"}</Text>
    </View>
  );
};

export default AgendaItem;

If I do:

const AgendaItem = ({ venue, organiser /*..etc*/ }) => {

I get undefined when I return them.

Any ideas?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Bomber
  • 10,195
  • 24
  • 90
  • 167
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Unpacking_fields_from_objects_passed_as_function_parameter – str Apr 13 '18 at 09:00
  • https://jsfiddle.net/joj8fc6a/2/ – Hammerbot Apr 13 '18 at 09:00

3 Answers3

2

From what i understand you item is an object and have your own properties.

You can do something like this:

const AgendaItem = ({ item: { venue, organiser, startTime, endTime, description } }) => {
  return (
    <View>
      <Text>Location: {venue}</Text>
      <Text>Consultant: {organiser}</Text>
      <Text>Time: {`${startTime} - ${endTime}`}</Text>
      <Text>Description: {description || "None"}</Text>
      <Text>Description: {description || "None"}</Text>
    </View>
  );
};

export default AgendaItem;
Nicolas Takashi
  • 1,550
  • 2
  • 10
  • 11
1

Try this instead const AgendaItem = ({item: { venue, organiser /*..etc*/ }}) => {

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Lewis
  • 14,132
  • 12
  • 66
  • 87
-1

const AgendaItem = ({ item }) => { ...

is the same as

const AgendaItem = (arg) => { const item = arg.item; ...


So if you do const AgendaItem = ({ venue, organiser ...etc }) => { and your object with an item attribute is still being passed, then venue, organiser, and etc will correctly be undfined since the engine will be looking for those properties in the argument object and not find them.

Meghan
  • 1,215
  • 11
  • 17