CID is returning as a object promise in app

I want to display the CID of the file uploaded to IPFS in the my app. The function that returns the CID value is in the below. However, although the file_hash value is a string here, the value returned by the function is Promise. When I try to display it in the app, it appears as [object promise]. However, I can see the CID value in the terminal.

...
async function hash_user_file(file_path, file_key) {
  encrypt_file(file_path, file_key);
  const encrypted_file_path = file_path + ".aes";
  const client = create({
    host: "ipfs.infura.io",
    port: 5001,
    protocol: "https",
    headers: {
      authorization: auth,
    },
  });
  const response = await client.add(encrypted_file_path);
  const file_hash = response.path.toString();
  console.log(file_hash);
  return file_hash;
}
...

The image above is the result of the terminal and image below is the result of the app:
External Image

How can I solve this problem? I would be glad if you help.

1 Like

The best way would be to display the CID through your dedicated gateway, something like:
const url = https://yourdedicatedgwname.infura-ipfs.io/ipfs/${file_hash}

This will probably be useful How to upload files on IPFS infura.io using React

2 Likes

Thanks for the reply. But is there a way to only display the CID? I searched a lot but couldn’t find any information about it.

1 Like

Please note that the reason why you see [object Promise] in your app instead of the actual CID value is because the hash_user_file function returns a Promise object that resolves to the CID value. In order to access the CID value, you need to wait for the Promise to resolve, either by using the await keyword or by chaining a .then() method to the Promise.

async function uploadAndHashFile(file_path, file_key) {
  encrypt_file(file_path, file_key);
  const encrypted_file_path = file_path + ".aes";
  const client = create({
    host: "ipfs.infura.io",
    port: 5001,
    protocol: "https",
    headers: {
      authorization: auth,
    },
  });
  const response = await client.add(encrypted_file_path);
  const file_hash = response.path.toString();
  console.log(file_hash);
  return file_hash;
}

// Call the function and wait for the Promise to resolve
async function displayCID() {
  const cid = await uploadAndHashFile(file_path, file_key);
  console.log(cid); // Should print the CID value to the console
  // Display the CID value in your app as desired
}

// Alternatively, you can use a .then() method to handle the Promise
function displayCID() {
  uploadAndHashFile(file_path, file_key).then(cid => {
    console.log(cid); // Should print the CID value to the console
    // Display the CID value in your app as desired
  });
}
3 Likes

It helped me to solve my problem. Thank you! :slight_smile:

2 Likes

This topic was automatically closed after 30 days. New replies are no longer allowed.