Arthur
Arthur

Reputation: 43

React upload and display image

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>

Upvotes: 0

Views: 1966

Answers (1)

Jamiryo
Jamiryo

Reputation: 92

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} />

Upvotes: 1

Related Questions