MdC
MdC

Reputation: 41

Axios request on button click

Why doesn't this function delete the quiz from the database, when it does work with Postman?

 deleteQuiz = () => {
    const quiz = this.state.quizData._id
     axios.delete(`http://localhost:5000/${quiz}`) 
    .then(res => {
      console.log(res.data)

  })

with an onClick:

<button onClick={() => this.deleteQuiz(this.state.quizData._id)}>Delete Quiz </button>

Similarly, this doesn't work:

topicSearch = topic => {
    axios.get(`http://localhost:5000/search/${topic}`)
        .then(res => {
            const data = res.data;
            this.setState({
                quizSelection: data
            })
        })
     }
}

with an onClick within a child component passing in topicSearch

 onClick={this.props.topicSearch}

But DOES work when calling topicSearch() inside the onChangeHandler and passing in the e.target.value

handleTopicChange = eventValue => {
    this.topicSearch(eventValue)
    this.setState({
        topic: topic
    })
}

From other examples it seems that passing state into functions is acceptable - is this something obvious that I am missing?

Upvotes: 0

Views: 4420

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

You are not getting any parameters here:

deleteQuiz = () => {
  const quiz = this.state.quizData._id;
  axios.delete(`http://localhost:5000/${quiz}`).then(res => {
    console.log(res.data);
  });
};

So use a parameter like this:

deleteQuiz = quiz => {
  axios.delete(`http://localhost:5000/${quiz}`).then(res => {
    console.log(res.data);
  });
};

And this will use the parameter passed and not the one from state.

<button onClick={() => this.deleteQuiz(this.state.quizData._id)}> Delete Quiz </button>

Upvotes: 1

Related Questions