Home > Software design >  Error: `FileSystem.moveAsync` needs a `to` path. in react native (Expo)
Error: `FileSystem.moveAsync` needs a `to` path. in react native (Expo)

Time:01-23

I am trying to take pictures from a real device and save it in a new location using expo expo-file-system. But I am getting an error Error: FileSystem.moveAsync needs a to path.

My code:

const fileMoveHandler = async () => {
    const fileName = selectedImage.split("/").pop();
    console.log("FileSystem:", FileSystem.documentDirectory   fileName);
    setNewPathImage(FileSystem.documentDirectory   fileName);
    console.log("newPathImage", newPathImage);
    try {
      await FileSystem.moveAsync({
        from: selectedImage,
        to: newPathImage,
      });
    } catch (err) {
      console.log("Error:", err);
      Alert.alert("Can't move this file.", "Try again!", [{ text: "Okay" }]);
    }
  };

Console.log:

FileSystem: file:///data/user/0/host.exp.exponent/files/ExperienceData/******/3061c494-6c3b-4307-abb3-a0d8681d2bb3.jpg

newPathImage undefined

Error: [Error: `FileSystem.moveAsync` needs a `to` path.]

As I am getting newPathImage undefined that's why it is giving me error but I don't know why I am getting undefined?

How can I set the state for the image path?

CodePudding user response:

It must be because setState() is asynchronous so when you try to set to to newPathImage it's still undefined. It should work if you do something like this instead:

const fileMoveHandler = async () => {
    const fileName = selectedImage.split("/").pop();
    const newPathImage = FileSystem.documentDirectory   fileName
    console.log("FileSystem:", newPathImage);
    setNewPathImage(newPathImage);
    console.log("newPathImage", newPathImage);
    try {
      await FileSystem.moveAsync({
        from: selectedImage,
        to: newPathImage,
      });
    } catch (err) {
      console.log("Error:", err);
      Alert.alert("Can't move this file.", "Try again!", [{ text: "Okay" }]);
    }
  };
  •  Tags:  
  • Related