Search code examples
javascriptobjectdestructuring

Destructuring nested params, undefined error


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") {

Solution

  • 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]