0

I don’t understand how to upload a photo correctly and then upload it to the page. I'm a beginner, can you please tell me what I did wrong?

const [photo, setPhoto] = useState('');

 const handleSubmit = (e) => {
        e.preventDefault();

        const users = {name, email, phone, position, photo}

        setIsPending(true);
        
        fetch("http://localhost:8000/users", {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify(users)
        }).then(() => {
            console.log('well');
            setIsPending(false);

        })
    }
<form className="form" onSubmit={handleSubmit}>
 
<UploadFile
 name="file"
 onChange={(e) => setPhoto(e.target.files[0])}
 value= {photo}
            
 />
<Button type="submit"/>
</form>

1 Answer 1

1

First of all you have to find a service that allows you to upload a file.

for example: https://api.imgur.com/endpoints/image/

there instructions inside.

However if you want to use fetch method I will give you an example how it should look like.

    const handleSubmission = () => {
        const formData = new FormData();

        formData.append('File', selectedFile);

        fetch(
            'https://freeimage.host/api/1/upload?key=<YOUR_API_KEY>',
            {
                method: 'POST',
                body: formData,
            }
        )
            .then((response) => response.json())
            .then((result) => {
                console.log('Success:', result);
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    };
    };

After recieving response from api service which is this part

.then((response) => response.json())
            .then((result) => {
                console.log('Success:', result);
            })
            .catch((error) => {
                console.error('Error:', error);
            });

You can set your state with the response url like this.

.then((response) => response.json())
            .then((result) => {
                console.log('Success:', result);
                setPhoto(result.data.imageurl)
            })
            .catch((error) => {
                console.error('Error:', error);
            });

In the end you can use that image anywhere you want.

<img src={photo} />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.