Using Promises with the fetch API and Redux
suggest changeRedux is the most common state management library used with React Native. The following example shows how to use the Fetch API and dispatch changes to your application's state with redux-thunk. recipeName, instructions, and ingredients are assumed to be in scope.
export const fetchRecipes = (action) => {
return (dispatch, getState) => {
fetch('/recipes', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
recipeName,
instructions,
ingredients
})
})
.then((res) => {
// If response was successful parse the json and dispatch an update
if (res.ok) {
res.json().then((recipe) => {
dispatch({
type: 'UPDATE_RECIPE',
recipe
});
});
} else {
// response wasn't successful so dispatch an error
res.json().then((err) => {
dispatch({
type: 'ERROR_RECIPE',
message: err.reason,
status: err.status
});
});
}
})
.catch((err) => {
// Runs if there is a general JavaScript error.
dispatch({
type: 'ERROR_RECIPE',
message: 'There was a problem with the request.'
});
});
};
};
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents