0

I need my code to run through this first & then I need to be able to retrieve the url from the API for later use.

const apiKey = "_____________"
const file = document.getElementById("file")
const img = document.getElementById("img")
const url = document.getElementById("image_url")
file.addEventListener("change", ev => {
    const formdata = new FormData()
    formdata.append("file", ev.target.files[0])
    formdata.append("upload_preset", apiKey)
    fetch("https://api.cloudinary.com/v1_1/dj6n2zg0o/image/upload", {
        method: "post",
        body: formdata
    }).then(data => data.json()).then(data => {
        // Updates Image on HTML page
        img.src = data.url
        // Renders URL onto HTML
        url.innerText = data.url
        // Need to get image_url variable to newFormHandler function
        return data.url
    })
});

After the images passes through API I need to pass the URL into this form handler:

const newFormHandler = async (event) => {
    event.preventDefault();
 
    const name = document.querySelector('#name').value.trim();
    const initial_price = document.querySelector('#initial_price').value.trim();
    const description = document.querySelector('#description').value.trim();
    if (name && initial_price && description) {
        const response = await fetch(`/api/products`, {
            method: 'POST',
            body: JSON.stringify({ name, initial_price, description }),
            headers: {
                'Content-Type': 'application/json',
            },
        });

        if (response.ok) {
            document.location.replace('/');
        } else {
            alert('Failed to create project');
        }
    }
};

document
  .querySelector('.new-product-form')
  .addEventListener('submit', newFormHandler);

Any advice would be greatly appreciated

mollysal
  • 1
  • 1
  • You could use a data placeholder tag in your HTML and query it, and there are also [other methods as shared in this link](https://stackoverflow.com/questions/10579713/passing-a-local-variable-from-one-function-to-another). – epasos_573 Oct 17 '22 at 07:34

1 Answers1

0

I figured it out. It turns out I needed a global variable to define the data & use in the form handler.

let storedData

file.addEventListener("change", ev => {
    const formdata = new FormData()
    formdata.append("file", ev.target.files[0])
    formdata.append("upload_preset", apiKey)
    fetch("https://api.cloudinary.com/v1_1/dj6n2zg0o/image/upload", {
        method: "post",
        body: formdata
    }).then(data => data.json()).then(data => {
        img.src = data.url
        url.innerText = data.url
        // Need to get image_url variable to newFormHandler function
        storedData = data
        console.log(storedData)
        return data.url
    })
});

The below was modified:

const newFormHandler = async (event) => {
    event.preventDefault();

    // Need url from storedData variable
    const {url} = storedData
    // const image_url = storedData.url
    // From Mini Project
    const name = document.querySelector('#name').value.trim();
    const initial_price = document.querySelector('#initial_price').value.trim();
    const description = document.querySelector('#description').value.trim();

    // Added image_url: url
    if (name && initial_price && description) {
        // Mini Project - const response = await fetch(`/api/projects`,
        const response = await fetch(`/api/products`, {
            method: 'POST',
            // Need to be key value pairs
            body: JSON.stringify({ name, initial_price, description, image_url: url }),
            headers: {
                'Content-Type': 'application/json',
            },
        });

        if (response.ok) {
            document.location.replace('/');
        } else {
            alert('Failed to create project');
        }
    }
};

document
  .querySelector('.new-product-form')
  .addEventListener('submit', newFormHandler);
mollysal
  • 1
  • 1