0

I'm trying to update a state inside a array map, but it gives me an error that setState is not a function on this. How can I acheive this? My code snippet is given below

this.setState({
  isLoading: true
});

this.state.questions.map(function(key, value) {
  if (key.id === undefined) {
    axios
      .post("/api/questions/create", key)
      .then(response => {
        this.setState({
          isLoading: true
        });
      })
      .catch(error => {});
  } else {
    axios
      .post("/api/questions/update/" + key.id, key)
      .then(response => {
        this.setState({
          isLoading: true
        });
      })
      .catch(error => {});
  }
});
3
  • Put this in a variable. Commented Feb 10, 2020 at 9:49
  • this.state.questions.map(function(key, value) { }) will not bind your this values but in ES6 arrow functions bind(this) keyword Commented Feb 10, 2020 at 10:12
  • you can also try this this.state.questions.map(function(key, value) { ...//stuff }).bind(this); Commented Feb 10, 2020 at 10:13

2 Answers 2

3

Try using a fat arrow syntax in your map instead.

Change this: this.state.questions.map(function(key, value) {

To this: this.state.questions.map((key, value) => {


An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.

Read more about arrow functions, here.

Sign up to request clarification or add additional context in comments.

Comments

1

Look into THIS for detailed working nature of this keyword and Arrow Functions for detailed info about => functions. Hope the docs helps in better understanding.

this.setState({
        isLoading: true,
    });

    this.state.questions.map((key, value) => {

      let that = this; // assigning this to a variable

        if ( key.id === undefined ) {

            axios.post('/api/questions/create', key)
                .then((response) => {

                   that.setState({ 
                        isLoading: true,
                    });

                })
                .catch((error) => {  

                });

        } else {

            axios.post('/api/questions/update/' + key.id, key)
                .then((response) => {

                    that.setState({
                        isLoading: true,
                    });

                })
                .catch((error) =>{

                });

        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.