0

Our code currently has a function that calls a toast message popup while saving an object to the database.

export function addAnimal(animalObject) {
  return function(dispatch) {
    showToastNotification(() => {
      return addAnimal(animalObject);
    }, dispatch);
  };
}


function showToastNotification(handleToastSave, dispatch) {    
  return handleToastSave()
    .then(() => {
      showMessage("this was a success")(dispatch);
    })
    .catch(() => {
      showMessage("Something went wrong!")(dispatch);
    })
    .finally(() => {
      saveMode(false)(dispatch);
    });
}

My question is I want to pass a message string as a parameter to the showToastNotification like this:

export function addAnimal(animalObject) {
  return function(dispatch) {
    showToastNotification(("successfully added animal") => {
      return addAnimal(animalObject);
    }, dispatch);
  };
}

function showToastNotification(message, handleToastSave, dispatch) {    
  return handleToastSave()
    .then(() => {
      showMessage(message)(dispatch);
    })
    .catch(() => {
      showMessage("Something went wrong!")(dispatch);
    })
    .finally(() => {
      saveMode(false)(dispatch);
    });
}

This doesn't work. I'm not super familiar with how the fat arrow in this function works. Would it be possible to pass a prop to showToastNotification?

1 Answer 1

2

You're putting the string where the parameters of the callback would be, instead of as the first argument to the actual showToastNotification function. Just move it to the right place:

showToastNotification("successfully added animal", () => {
  return addAnimal(animalObject);
}, dispatch);
Sign up to request clarification or add additional context in comments.

2 Comments

do you know where's the best place I can find resources about fat arrow functions like this? I still don't 100% understand the syntax
If you Google "ES6 arrow function" you can find plenty. But it's fairly simple. Where you would previously create an anonymous function by doing function(param1, param2, param3) { /* Code here */ } you can now write it like (param1, param2, param3) => { /* Code here */ } Instead. If you just want the function to be a single line that returns the result of that line, you can remove the {} and the word "return" if you like; (p1, p2, p3) => p1+p2+p3 will add the parameters and return the sum, for instance. In arrow functions, this refers to the outer scope instead of the function scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.