Home > Net >  Submit handler, React Axios: Post and Get in same handler
Submit handler, React Axios: Post and Get in same handler

Time:11-24

I am trying to create a web app that uploads file and attached the current user to the file model as a foreign key. For some reason the get request is being wiped, but it does initially get the needed information.

  handleSubmit = (e) => {
    e.preventDefault();
    axios.get('http://127.0.0.1:8000/core/current_user/', {
      headers: {
        Authorization: `JWT ${localStorage.getItem('token')}`,
      }
    }).then((user) => {

      this.state.creator = user.data;
      console.log(this.state.creator);
    })  
    console.log(this.state.creator);
    let form_data = new FormData();
    form_data.append('creator', this.state.creator);
    form_data.append('file', this.state.file);
    form_data.append('title', this.state.title);
    form_data.append('description', this.state.description);
    axios.post('http://localhost:8000/core/posts/', form_data, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `JWT ${localStorage.getItem('token')}`,
      }
    }).then(res => {
        console.log(res.data);
      }).catch(err => console.log(err))
  };

The 1st console is returning the user information but the 2nd console returns null. Any help will be really appreciated.

CodePudding user response:

Your then statement after the original get ends on line 11, and the rest of your code is outside of that.

With asynchronous code, the code outside of the then block will continue running while it's waiting for a response, so this.state.creator will not have been set yet. Then it will return to the code inside the then block once the promise resolves.

You need to move all of the second block of code inside the intial then block so it is only executed once a response to the original get request has returned:

handleSubmit = e => {
    e.preventDefault();
    axios
        .get('http://127.0.0.1:8000/core/current_user/', {
            headers: {
                Authorization: `JWT ${localStorage.getItem('token')}`
            }
        })
        .then(user => {
            this.state.creator = user.data;
            console.log(this.state.creator);
            let form_data = new FormData();
            form_data.append('creator', this.state.creator);
            form_data.append('file', this.state.file);
            form_data.append('title', this.state.title);
            form_data.append('description', this.state.description);
            axios
                .post('http://localhost:8000/core/posts/', form_data, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        Authorization: `JWT ${localStorage.getItem('token')}`
                    }
                })
                .then(res => {
                    console.log(res.data);
                })
                .catch(err => console.log(err));
        });
};
  • Related