-1

I keep getting payload undefined when destructuring:

let videosArray = [];
if (payload.videos) {
  const {
    payload: { videos }
  } = action;
  videosArray = videos;
}

return videosArray;

How can I check for undefined? I have tried the check below, but keep getting the error:

   if (typeof payload !== "undefined") {
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Bomber
  • 10,195
  • 24
  • 90
  • 167

3 Answers3

0

You need to have action defined like this const action = {payload: {videos: ["Matrix", "Star Wars"]}}

And you can check that payload is not undefined like this if(action && action.payload) then you could do your destructing operation.

zagoa
  • 798
  • 4
  • 23
0

You just have to make sure the action is defined first, and access its parameters instead of calling payload by itself. In your example it looks as if payload was undeclared when you try to access it

function getVideos(action) {
  if (action && action.payload && action.payload.videos) {
    const {payload: {videos}} = action;
    return videos;
  }

  return [];
}

console.log(getVideos()); // action undefined, expected []
console.log(getVideos({})); // payload undefined, expected []
console.log(getVideos({payload: {}})); // videos undefined, expected []
console.log(getVideos({payload: {videos: [1,2,3]}})); // expected [1,2,3]

Of course if you really wanted to complete the task with just destructuring you could simply create some default values like this:

function getVideos(action) {
  const {payload: {videos=[]}={}} = action || {};
  return videos;
}

console.log(getVideos()); // action undefined, expected []
console.log(getVideos({})); // payload undefined, expected []
console.log(getVideos({payload: {}})); // videos undefined, expected []
console.log(getVideos({payload: {videos: [1,2,3]}})); // expected [1,2,3]
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
0

You could take a check and a default value without destructuring.

function getVideos(action) {
    return action && action.payload && action.payload.videos || [];
}

console.log(getVideos());                 // action undefined, expected []
console.log(getVideos({}));              // payload undefined, expected []
console.log(getVideos({ payload: {} }));  // videos undefined, expected []
console.log(getVideos({ payload: { videos: [1, 2, 3] } })); // expected [1, 2, 3]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392