0

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.

1 Answer 1

1

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.

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

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.