Reputation: 61
I'm trying to update my database using react/redux and I am at a loss as to how. From what I understand it can be done using a fetch post request. I'm trying to do this in my action creators but i think my overall understanding of the syntax of a post request is lacking.
If i could get an example of the proper way to use fetch to use a post request i'd appreciate it, or even a link to the right direction.
Upvotes: 0
Views: 325
Reputation: 1532
I took the fetch example from the Mozilla docs:
export function postDataSuccess(response) {
return {
type: 'POST_SOMETHING',
response
};
}
export function postData(url, data) {
return dispatch => {
fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => dispatch( postDataSuccess(response.json()) ));
}
}
Then in your code you can use postData whenever you need to make the action, and in your reducers to listen for 'POST_SOMETHING' action.
Upvotes: 1