kilogram
kilogram

Reputation: 717

How to send a fetch post request from react component to backend

enter image description here

I want to send the fetch post request to the server from react class component. I never did fetch post. So how can I do this from that component using thunk.

class Add extends Component {
	constructor(props) {
		super(props);
		this.state = {username: '', email:'', text:''};
		this.handleChange = this.handleChange.bind(this);
		this.handleSubmit = this.handleSubmit.bind(this);
	}
	handleChange(event) {
		this.setState({value: event.target.value});
	}
	
	handleSubmit(event) { 
                alert (JSON.stringify(this.state))
		event.preventDefault();
	}
	render(){
		return (
		<div className="addcontainer">
		<div style={{display: 'flex', justifyContent: 'center'}}>
		<h4>Add new task here:</h4>
		</div>
		<form onSubmit={this.handleSubmit}>
		<div className="wrapper">
			<label for="username"><b>Username</b></label>
			<input type="text" value={this.state.username} onChange={e => this.setState({ username: e.target.value })} placeholder="Enter Username" name="uname" required />
			<label for="email"><b>Email</b></label>
			<input type="text" value={this.state.password} onChange={e => this.setState({ email: e.target.value })} placeholder="Enter Email" name="email" required />
			<label for="text"><b>Text</b></label>
			<input type="text" value={this.state.password} onChange={e => this.setState({ text: e.target.value })} placeholder="Enter Task" name="text" required />
			<button className="login" type="submit">Add task</button>	
		</div>
		</form>
		</div>
		)
	}
}

I also have an example of the jquery ajax request in documentation, but it is of little help to me. Please help me to write thunk with fetch

  $(document).ready(function() {
    var form = new FormData();
    form.append("username", "Example");
    form.append("email", "[email protected]");
    form.append("text", "Some text");

    $.ajax({
        url: 'https://uxcandy.com/~shapoval/test-task-backend/create?developer=Example',
        crossDomain: true,
        method: 'POST',
        mimeType: "multipart/form-data",
        contentType: false,
        processData: false,
        data: form,
        dataType: "json",
        success: function(data) {
            console.log(data);
        }
    });
});  

Here is thunk that works with fetch get:

const getRepos = username => async dispatch => {
  try {
    var url = `https://uxcandy.com/~shapoval/test-task-backend/?developer=sait&sort_field=${username}`;
    const response = await fetch(url);
    const responseBody = await response.json();
    //console.log(responseBody.message.tasks);
    dispatch(addRepos(responseBody.message.tasks));
  } catch (error) {
    console.error(error);
    dispatch(clearRepos());
  }
};

Upvotes: 3

Views: 8633

Answers (1)

Umair Farooq
Umair Farooq

Reputation: 1823

You can use second argument of fetch function to add options e.g.

fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, cors, *same-origin
    cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
    credentials: "same-origin", // include, *same-origin, omit
    headers: {
        "Content-Type": "application/json",
        // "Content-Type": "application/x-www-form-urlencoded",
    },
    redirect: "follow", // manual, *follow, error
    referrer: "no-referrer", // no-referrer, *client
    body: JSON.stringify(data), // body data type must match "Content-Type" header
})

For more information please refer here

other effective way to make api hit is by using axios

Upvotes: 4

Related Questions