Search code examples
javascriptreactjsfilemultipartform-dataform-data

React Problem : I tried file data set in state when upload file, but it isn't work


First, I am not a english native. So, my sentence can be wrong grammatically or can be difficult to convey meaning.

I have a React Project with Laravel and Axios. I want to upload image data on my server. So, I tried set file data in state when file is uploaded to follow this document, but it doesn't work.

I want to know reason why it isn't work.

Here is some of my code.

import Axios from 'axios';
import React, { Component } from 'react';

class Register extends Component {
  constructor() {
    super();
    this.state = {
      name: '',
      email: '',
      password: '',
      password_confirmation: '',
      profile_picture: null,
      errors: [],
    }

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.hasErrorFor = this.hasErrorFor.bind(this);
    this.renderErrorFor = this.renderErrorFor.bind(this);
  }

  handleChange(event) {
    if(event.target.name.match('profile_picture')) {
      // when input profile picture
      this.setState({
        [event.target.name]: event.target.files[0],
      });

      console.log(event.target.files[0]);
    } else {
      // when input text values
      this.setState({
        [event.target.name]: event.target.value,
      });
    }

    console.log(this.state);
  }

  handleSubmit(event) {
    // submit event
  }

  hasErrorFor(field) {
    // detect error
  }

  renderErrorFor(field) {
    // render error message
  }

  render() {  
    return (
      <div className="container">
        <div className="row justify-content-center">
          <div className="col-md-8">
            <div className="card">
              <div className="card-header">Register</div>
              <div className="card-body">
                <form 
                  action="/api/register"
                  method="post"
                  encType='application/x-www-form-urlencoded'
                  onSubmit={this.handleSubmit}
                >
                  <div className="form-group">
                    // input name
                  </div>

                  <div className="form-group">
                    // input email
                  </div>

                  <div className="form-group">
                    // input password
                  </div>

                  <div className="form-group">
                    // input password confirmation
                  </div>

                  <div className="form-group">
                    <label htmlFor="profile_picture">Profile Picture</label>
                    <input
                      id="profile_picture" 
                      type="file"
                      name="profile_picture"
                      className='form-control-file'                      
                      onChange={this.handleChange}
                    />
                    {this.renderErrorFor('profile_picture')}
                  </div>

                  <button className="btn btn-primary">SUBMIT</button>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Register;

And here is result of this code.

I except the uploaded file is set in state when I upload a file, but file doesn't set in state.


Solution

  • you've written console.log() immediately after setState method, since setState is an async method an at the time java script runs your console.log it will be showing you the previous state in which obviously image object is not set, for this you should put your console in the second argument of setState that is a callback function.

    this.setState({[event.target.name]: event.target.files[0]},()=>console.log(this.state));