Saeed Aftabi
Saeed Aftabi

Reputation: 1

How can I convert functions in class-based component to functional components in React?

I'm trying to convert my class-based React component to a functional component. How should I convert functions like:

onFileUpload = async () => {

        const formData = new FormData();

        formData.append(
            "ImageData.File",
            this.state.selectedFile,
            this.state.selectedFile.name
        );



        fetch('/api/Image', {
            method: 'POST',
            body: formData
        }).then(resposne => resposne.json())
            .then(data => {
                console.log(data);
                this.setState({ uploadResult: "File " + data.fileName + " successfully uploaded." });
                this.getList();
            });

    };

The whole code comes here: https://drive.google.com/file/d/1YSSMTGkxzeH1R1V2rgQkwl1QwxnoXtuq/view?usp=sharing

Upvotes: 0

Views: 58

Answers (2)

Nick Carbone
Nick Carbone

Reputation: 218

You are going to replace this.state.selectedFile with:

const [selectedFile, setSelectedFile] = useState() // and pass useState the initial state

When you need to update selectedFile you will call setSelectedFile() with the new data.

This is the same for uploadResult

Upvotes: 0

Nikita Mazur
Nikita Mazur

Reputation: 1785

const FuncComponent = () => {
    const onFileUpload = async () => {
       // do magic here
    }
    return <div />
}

Upvotes: 1

Related Questions