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

Time:02-25

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.

  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?

CodePudding user response:

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",
  })
);
  • Related