export function fetchContacts(filter) {
return async (dispatch) => {
try {
let url = "http://localhost:3000/contacts";
if (filter) {
url = "http://localhost:3000/contacts?category=" + filter;
}
let data = await fetch(url);
let response = await data.json();
dispatch({
type: "contacts/fetchContacts",
payload: response,
});
} catch (error) {
console.log(error);
}
};
}
export function deleteContacts(id) {
return async (dispatch) => {
try {
let url = `http://localhost:3000/contacts/${id}`;
let data = await fetch(url, {
method: "DELETE",
"Content-Type": "application.json",
});
let response = await data.json();
dispatch(fetchContacts());
return response;
} catch (error) {
console.log(error);
}
};
}
export function contactDetail(id) {
return async (dispatch) => {
try {
let url = `http://localhost:3000/contacts/${id}`;
let data = await fetch(url, {
method: "GET",
"Content-Type": "application.json",
});
let response = await data.json();
dispatch({
type: "contact/contactDetail",
payload: response,
});
} catch (error) {
console.log(error);
}
};
}
export function addContact(name, phoneNumber, email, category) {
return async (dispatch) => {
try {
let url = `http://localhost:3000/contacts`;
let data = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: name,
phoneNumber: phoneNumber,
email: email,
category: category,
}),
});
let response = await data.json();
console.log(name);
dispatch(fetchContacts());
} catch (error) {
console.log(error);
}
};
}
export function fetchProducts() {
return dispatch => {
dispatch(fetchProductsBegin());
return fetch("/products")
.then(handleErrors)
.then(res => res.json())
.then(json => {
dispatch(fetchProductsSuccess(json.products));
return json.products;
})
.catch(error => dispatch(fetchProductsFailure(error)));
};
}
// Handle HTTP errors since fetch won't.
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}