Yassine Ghz
Yassine Ghz

Reputation: 77

Reactjs - state updating - Ajax - Axios

Im trying to update my states after a form submit , without refreshing the page. part of my ReactJs code :

export default class DashboardRA extends Component {

constructor(props)
{
    super(props);
    this.state = {
      json:JSON.parse(props.data),//data received from a laravel controller used to implement the page.
      pdf: '',
    ...
    ...


    async onSubmitButton(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("pdf", this.state.pdf);
    ...
    const response = await axios.post("/uploadFile", formData, {
    headers: {
    "Content-Type": "multipart/form-data"
    }
    })
    .then(function (response) {
      // console.log(response.data); //data from the DB
      this.setState({
        json:JSON.parse(response.data)
      });
    })
    .catch(err => { 
        console.log(err);
        this.setState({errorMessage: err.message});    
    })
}

but it shows the following error : Cannot read property 'setState' of undefined

Upvotes: 0

Views: 46

Answers (2)

Hosny Ben
Hosny Ben

Reputation: 136

It will be because your trying to acces to a method which is no defined in your response function. You have to assign this to variable before running axios. please check this out

export default class DashboardRA extends Component {

constructor(props)
{
    super(props);
    this.state = {
      json:JSON.parse(props.data),//data received from a laravel controller used to implement the page.
      pdf: '',
    ...
    ...


    async onSubmitButton(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("pdf", this.state.pdf);
    ...


    const my_this = this;


    const response = await axios.post("/uploadFile", formData, {
    headers: {
    "Content-Type": "multipart/form-data"
    }
    })
    .then(function (response) {
      // console.log(response.data); //data from the DB
      my_this.setState({
        json:JSON.parse(response.data)
      });
    })
    .catch(err => { 
        console.log(err);
        my_this.setState({errorMessage: err.message});    
    })
}

Upvotes: 1

dkuznietsov
dkuznietsov

Reputation: 298

Just change your code to

.then((response) => {
  // console.log(response.data); //data from the DB
  this.setState({
    json:JSON.parse(response.data)
  });
})

You're gwtting the error because when you refer to this in function you refer to whatever context this function is called in (some Promise internals). By using arrow syntax you're automatically binding it to the context it's declared in (component in your case)

Upvotes: 1

Related Questions