Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

action for fetch item redux

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);
    }
  };
}
 
PREVIOUS NEXT
Tagged: #action #fetch #item #redux
ADD COMMENT
Topic
Name
7+2 =