ReactJs displays error Cannot read property setState of undefined with Axios form submission










1















ReactJs displays the error:




Cannot read property setState of undefined.




I know that this question has been asked more often but most solutions I found do not address my current problem.



This code below was used to post files to server and it works fine. Now If I implement the code below immediately after the Axios response returns:



this.setState(
filename:res.data.filename,
message:res.data.message,
);


It will display said error. Please which setState do I need to bind



Here is the code



import React, Component from 'react';
import $ from 'jquery';
import axios, post from 'axios';

class FilePage extends React.Component
constructor(props)
super(props);
this.state =
value:'',
filename:'',
myfile:'',
submitted: false
;

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);


handleChange(event)
this.setState( [event.target.name]: event.target.value );


handleSubmit(event)
event.preventDefault();
this.setState( submitted: true );

var formData = new FormData();
formData.append('myfile', $('#myfile')[0].files[0]);
formData.append('filename', $('#filename').val());

axios
.post('http://localhost/api.php', formData)
.then(function (res)
console.log(res);
this.setState(
filename:res.data.filename,
message:res.data.message,
);
)
.catch(function (err)
console.log(err.message);
);


render()
const submitted = this.state;
var style1 =
background: 'green',
color: 'white',
fontSize: 30
;

return (
<form onSubmit=this.handleSubmit id="myform">
<label>
<div style=style1> Testing Data </div>
<input className="form-control" name="myfile" type="file" id="myfile" value=this.state.myfile onChange=this.handleChange />
<b>filename:</b><input tyle="text" className="form-control" value=this.state.filename name="filename" onChange=this.handleChange />
</label>
<input className="btn btn-primary" type="submit" value="Submit" id="btn"/>
</form>
);











share|improve this question
























  • function(res) disconnects the this context in your success callback, use an arrow function there (same goes for function(err) but you are not referring to thisat that time. Also, when you look for help, take some effort in formatting your code, cause as it is at the moment it's quite a jumble...

    – Icepickle
    Nov 14 '18 at 21:35












  • Please Icepickle can you illustrate with example

    – jmarkatti
    Nov 14 '18 at 21:36











  • I am sorry but if this is not clear how this scope is handled, then you really should learn javascript and scopes / context a bit more in detail. In the meantime, an answer got added that gives you a solution, though it might not directly expand on the why. It is by far not the only problem in your code (though the problems I would be referring to would be react specific things)

    – Icepickle
    Nov 14 '18 at 21:38
















1















ReactJs displays the error:




Cannot read property setState of undefined.




I know that this question has been asked more often but most solutions I found do not address my current problem.



This code below was used to post files to server and it works fine. Now If I implement the code below immediately after the Axios response returns:



this.setState(
filename:res.data.filename,
message:res.data.message,
);


It will display said error. Please which setState do I need to bind



Here is the code



import React, Component from 'react';
import $ from 'jquery';
import axios, post from 'axios';

class FilePage extends React.Component
constructor(props)
super(props);
this.state =
value:'',
filename:'',
myfile:'',
submitted: false
;

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);


handleChange(event)
this.setState( [event.target.name]: event.target.value );


handleSubmit(event)
event.preventDefault();
this.setState( submitted: true );

var formData = new FormData();
formData.append('myfile', $('#myfile')[0].files[0]);
formData.append('filename', $('#filename').val());

axios
.post('http://localhost/api.php', formData)
.then(function (res)
console.log(res);
this.setState(
filename:res.data.filename,
message:res.data.message,
);
)
.catch(function (err)
console.log(err.message);
);


render()
const submitted = this.state;
var style1 =
background: 'green',
color: 'white',
fontSize: 30
;

return (
<form onSubmit=this.handleSubmit id="myform">
<label>
<div style=style1> Testing Data </div>
<input className="form-control" name="myfile" type="file" id="myfile" value=this.state.myfile onChange=this.handleChange />
<b>filename:</b><input tyle="text" className="form-control" value=this.state.filename name="filename" onChange=this.handleChange />
</label>
<input className="btn btn-primary" type="submit" value="Submit" id="btn"/>
</form>
);











share|improve this question
























  • function(res) disconnects the this context in your success callback, use an arrow function there (same goes for function(err) but you are not referring to thisat that time. Also, when you look for help, take some effort in formatting your code, cause as it is at the moment it's quite a jumble...

    – Icepickle
    Nov 14 '18 at 21:35












  • Please Icepickle can you illustrate with example

    – jmarkatti
    Nov 14 '18 at 21:36











  • I am sorry but if this is not clear how this scope is handled, then you really should learn javascript and scopes / context a bit more in detail. In the meantime, an answer got added that gives you a solution, though it might not directly expand on the why. It is by far not the only problem in your code (though the problems I would be referring to would be react specific things)

    – Icepickle
    Nov 14 '18 at 21:38














1












1








1








ReactJs displays the error:




Cannot read property setState of undefined.




I know that this question has been asked more often but most solutions I found do not address my current problem.



This code below was used to post files to server and it works fine. Now If I implement the code below immediately after the Axios response returns:



this.setState(
filename:res.data.filename,
message:res.data.message,
);


It will display said error. Please which setState do I need to bind



Here is the code



import React, Component from 'react';
import $ from 'jquery';
import axios, post from 'axios';

class FilePage extends React.Component
constructor(props)
super(props);
this.state =
value:'',
filename:'',
myfile:'',
submitted: false
;

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);


handleChange(event)
this.setState( [event.target.name]: event.target.value );


handleSubmit(event)
event.preventDefault();
this.setState( submitted: true );

var formData = new FormData();
formData.append('myfile', $('#myfile')[0].files[0]);
formData.append('filename', $('#filename').val());

axios
.post('http://localhost/api.php', formData)
.then(function (res)
console.log(res);
this.setState(
filename:res.data.filename,
message:res.data.message,
);
)
.catch(function (err)
console.log(err.message);
);


render()
const submitted = this.state;
var style1 =
background: 'green',
color: 'white',
fontSize: 30
;

return (
<form onSubmit=this.handleSubmit id="myform">
<label>
<div style=style1> Testing Data </div>
<input className="form-control" name="myfile" type="file" id="myfile" value=this.state.myfile onChange=this.handleChange />
<b>filename:</b><input tyle="text" className="form-control" value=this.state.filename name="filename" onChange=this.handleChange />
</label>
<input className="btn btn-primary" type="submit" value="Submit" id="btn"/>
</form>
);











share|improve this question
















ReactJs displays the error:




Cannot read property setState of undefined.




I know that this question has been asked more often but most solutions I found do not address my current problem.



This code below was used to post files to server and it works fine. Now If I implement the code below immediately after the Axios response returns:



this.setState(
filename:res.data.filename,
message:res.data.message,
);


It will display said error. Please which setState do I need to bind



Here is the code



import React, Component from 'react';
import $ from 'jquery';
import axios, post from 'axios';

class FilePage extends React.Component
constructor(props)
super(props);
this.state =
value:'',
filename:'',
myfile:'',
submitted: false
;

this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);


handleChange(event)
this.setState( [event.target.name]: event.target.value );


handleSubmit(event)
event.preventDefault();
this.setState( submitted: true );

var formData = new FormData();
formData.append('myfile', $('#myfile')[0].files[0]);
formData.append('filename', $('#filename').val());

axios
.post('http://localhost/api.php', formData)
.then(function (res)
console.log(res);
this.setState(
filename:res.data.filename,
message:res.data.message,
);
)
.catch(function (err)
console.log(err.message);
);


render()
const submitted = this.state;
var style1 =
background: 'green',
color: 'white',
fontSize: 30
;

return (
<form onSubmit=this.handleSubmit id="myform">
<label>
<div style=style1> Testing Data </div>
<input className="form-control" name="myfile" type="file" id="myfile" value=this.state.myfile onChange=this.handleChange />
<b>filename:</b><input tyle="text" className="form-control" value=this.state.filename name="filename" onChange=this.handleChange />
</label>
<input className="btn btn-primary" type="submit" value="Submit" id="btn"/>
</form>
);








reactjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 21:54









Icepickle

8,81332136




8,81332136










asked Nov 14 '18 at 21:31









jmarkattijmarkatti

17719




17719












  • function(res) disconnects the this context in your success callback, use an arrow function there (same goes for function(err) but you are not referring to thisat that time. Also, when you look for help, take some effort in formatting your code, cause as it is at the moment it's quite a jumble...

    – Icepickle
    Nov 14 '18 at 21:35












  • Please Icepickle can you illustrate with example

    – jmarkatti
    Nov 14 '18 at 21:36











  • I am sorry but if this is not clear how this scope is handled, then you really should learn javascript and scopes / context a bit more in detail. In the meantime, an answer got added that gives you a solution, though it might not directly expand on the why. It is by far not the only problem in your code (though the problems I would be referring to would be react specific things)

    – Icepickle
    Nov 14 '18 at 21:38


















  • function(res) disconnects the this context in your success callback, use an arrow function there (same goes for function(err) but you are not referring to thisat that time. Also, when you look for help, take some effort in formatting your code, cause as it is at the moment it's quite a jumble...

    – Icepickle
    Nov 14 '18 at 21:35












  • Please Icepickle can you illustrate with example

    – jmarkatti
    Nov 14 '18 at 21:36











  • I am sorry but if this is not clear how this scope is handled, then you really should learn javascript and scopes / context a bit more in detail. In the meantime, an answer got added that gives you a solution, though it might not directly expand on the why. It is by far not the only problem in your code (though the problems I would be referring to would be react specific things)

    – Icepickle
    Nov 14 '18 at 21:38

















function(res) disconnects the this context in your success callback, use an arrow function there (same goes for function(err) but you are not referring to thisat that time. Also, when you look for help, take some effort in formatting your code, cause as it is at the moment it's quite a jumble...

– Icepickle
Nov 14 '18 at 21:35






function(res) disconnects the this context in your success callback, use an arrow function there (same goes for function(err) but you are not referring to thisat that time. Also, when you look for help, take some effort in formatting your code, cause as it is at the moment it's quite a jumble...

– Icepickle
Nov 14 '18 at 21:35














Please Icepickle can you illustrate with example

– jmarkatti
Nov 14 '18 at 21:36





Please Icepickle can you illustrate with example

– jmarkatti
Nov 14 '18 at 21:36













I am sorry but if this is not clear how this scope is handled, then you really should learn javascript and scopes / context a bit more in detail. In the meantime, an answer got added that gives you a solution, though it might not directly expand on the why. It is by far not the only problem in your code (though the problems I would be referring to would be react specific things)

– Icepickle
Nov 14 '18 at 21:38






I am sorry but if this is not clear how this scope is handled, then you really should learn javascript and scopes / context a bit more in detail. In the meantime, an answer got added that gives you a solution, though it might not directly expand on the why. It is by far not the only problem in your code (though the problems I would be referring to would be react specific things)

– Icepickle
Nov 14 '18 at 21:38













1 Answer
1






active

oldest

votes


















1














The scope inside the function(res) is changed. Try this instead.



axios.post('http://localhost/api.php', formData)
.then((res) => {
console.log(res);

this.setState(
filename:res.data.filename,
message:res.data.message,

);





share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309035%2freactjs-displays-error-cannot-read-property-setstate-of-undefined-with-axios-for%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    The scope inside the function(res) is changed. Try this instead.



    axios.post('http://localhost/api.php', formData)
    .then((res) => {
    console.log(res);

    this.setState(
    filename:res.data.filename,
    message:res.data.message,

    );





    share|improve this answer



























      1














      The scope inside the function(res) is changed. Try this instead.



      axios.post('http://localhost/api.php', formData)
      .then((res) => {
      console.log(res);

      this.setState(
      filename:res.data.filename,
      message:res.data.message,

      );





      share|improve this answer

























        1












        1








        1







        The scope inside the function(res) is changed. Try this instead.



        axios.post('http://localhost/api.php', formData)
        .then((res) => {
        console.log(res);

        this.setState(
        filename:res.data.filename,
        message:res.data.message,

        );





        share|improve this answer













        The scope inside the function(res) is changed. Try this instead.



        axios.post('http://localhost/api.php', formData)
        .then((res) => {
        console.log(res);

        this.setState(
        filename:res.data.filename,
        message:res.data.message,

        );






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 21:36









        ub3rst4rub3rst4r

        1,7771731




        1,7771731





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309035%2freactjs-displays-error-cannot-read-property-setstate-of-undefined-with-axios-for%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            政党

            天津地下鉄3号線