Skip to content

Instantly share code, notes, and snippets.

@leslie-alldridge
Last active September 22, 2018 07:28
Show Gist options
  • Save leslie-alldridge/83b7c9c135ad1353aec73d501afa12dc to your computer and use it in GitHub Desktop.
Save leslie-alldridge/83b7c9c135ad1353aec73d501afa12dc to your computer and use it in GitHub Desktop.
Actions
//all func below this line are for deleting a bag
//this function will tell our react front end to wait, while we go and fetch a bag. You can use something like
//if (this.props.isFetching == true) {display a loading spinner}
//this action will display in Redux dev tools as 'BAG_DEL_REQ' with it's relevant information.
function deleteReqBag(id) {
return {
type: "BAG_DEL_REQ",
isFetching: true,
isAuthenticated: true,
id
};
}
//this function is called after the API responds, we capture the response and assign it to Redux's state as response.
//since these are actions, our combined reduces will access the info by going 'action.response'
function receiveDelBag(response) {
return {
type: "BAG_DEL_DONE",
isFetching: false,
isAuthenticated: true,
response: response
};
}
//This function does the API request!! This is the function we call from the React front end. Remember, it's this.props.deleteBagDB.
//So what does it do?
export function deleteBagDB(id) {
return function(dispatch) {
dispatch(deleteReqBag(id)); //set a new redux state to let our application know we're going to wait for a while
request("post", "/bagsdel", { id: id }).then(response => { //contacts our server - post request to /bagsdel
if (!response.ok) {
console.log("an error occurred")
} else {
dispatch(receiveDelBag(response.body.bag)); //if a response comes back, tell our app to stop waiting and save the data in Redux's state!
}
});
};
}
@leslie-alldridge
Copy link
Author

The API request is using super agent (import request from 'superagent')
the third parameter is data we're posting to the server

request("post", "/bagsdel", { id: id })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment