| 0 | kirasiris | Categories: Tags: , , , , ,

First let’s take a look in Axios and Fetch, two libraries that help us make requests to API endpoints and so on. Both of them are good and work great but Fetch is native from the browser while Axios is external.

On the first screenshot I’m using dispatch to throw an error message but they’re not necessary to include.

Axios is a library that facilitates the syntax, I mean, most of the time the only config you will have to set up by yourself is the header, otherwise its is pretty simple to use; you only define axios.METHOD and that’s it, it works!

export const forgotpassword = formData => async dispatch => {
  try {
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    };

    const res = await axios.post(
      `/api/v1/auth/forgotpassword`,
      formData,
      config
    );

    dispatch({
      type: RECOVERY_SENT,
      payload: res.data
    });

    dispatch(setAlert('Please check your email', 'success'));
  } catch (err) {
    const errors = err.response.data.errors;
    if (errors) {
      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
    }
    dispatch({
      type: RECOVERY_FAIL
    });
    dispatch(setAlert('Invalid credentials', 'danger'));
  }
};

Fetch which is the one I’m moving my applications to, requires less lines of code and is still eligible when reading its logic:

export const forgotpassword = forgotData => {
  const config = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(forgotData)
  };
  return fetch(`${API}/api/v1/auth/forgotpassword`, config)
    .then(res => {
      return res.json();
    })
    .catch(err => {
      const errors = err.response.data.errors;
      if (errors) {
        errors.forEach(error => console.log(error.msg));
      }
    });
};

In conclusion for me, both of them are great to use but Fetch is the one most of the developers use, so I rather stay with it so I can get help if I ever get stuck in something!. Throwing errors is also easy but that is going to be for another post.

Remember to check my previous posts and/or snippets if you have found this article to be useful. Have a great day and Bye-Bye 🙂 .

Leave a Reply

Back to Top