Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why map() function can't make a new Array?

I use react-native with graphQL.

selectPhoto is an array containing two strings.

Array [
  "file:///storage/emulated/0/DCIM/Camera/20220223_150530.jpg",
  "file:///storage/emulated/0/DCIM/Camera/20220223_150453.jpg",
] 

and I use map to make new array with this array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const onValid = async ({ caption }) => {
    const file = selectPhoto.map((sp, index) => {
      console.log(sp, index);
      new ReactNativeFile({
        uri: sp,
        name: `${index}.jpg`,
        type: "image/jpeg",
      });
    });
    console.log(file);
  };

when i console.log(sp, index) here, each string and index is recorded correctly.

But when I make this file then console.log it,

I expect thing like below.

Array [
  ReactNativeFile {
    "name": "0.jpg",
    "type": "image/jpeg",
    "uri": "file:///storage/emulated/0/DCIM/Screenshots/Screenshot_20220223-011625_KakaoTalk.jpg",
  },
  ReactNativeFile {
    "name": "1.jpg",
    "type": "image/jpeg",
    "uri": "file:///storage/emulated/0/DCIM/Camera/20220222_161411.jpg",
  },
]

However, this Array of undefined comes.

Array [
  undefined,
  undefined,
]

Even I tried with Promise.all as below.
But still the same as undefined.

  const onValid = async ({ caption }) => {
    const file = Promise.all(
      selectPhoto.map((sp, index) => {
        console.log(sp, index);
        new ReactNativeFile({
          uri: sp,
          name: `${index}.jpg`,
          type: "image/jpeg",
        });
      })
    );

Can you know what the problem is here?

>Solution :

Why map() function can’t make a new Array?

It does make a new Array, but it fills it with undefined.

You need a return in there. A function in javascript without a return, will return undefined.

selectPhoto.map((sp, index) => {
  console.log(sp, index);

  //here you need to return the ReactNativeFile you just created:
  return new ReactNativeFile({
    uri: sp,
    name: `${index}.jpg`,
    type: "image/jpeg",
  });
});

If you wouldn’t start a code block (without the {}), then it would work without the return keyword:

selectPhoto.map((sp, index) => new ReactNativeFile({
    uri: sp,
    name: `${index}.jpg`,
    type: "image/jpeg",
  })
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading