maryvilledev / skilldirectoryui

React front-end for the Skill Directory API
0 stars 0 forks source link

Discuss Adding "Util" File #39

Open Hopding opened 7 years ago

Hopding commented 7 years ago

I think it would be useful to add a utilities file for holding generic, often used functions to avoid duplicating them and to make them easy to find - similar to what we have in the backend. Networking functions are prime candidates for this.

For example, I've created the following functions for the PR I'm working on right now:

// Invokes callback with total Team Member records in the api backend as param.
function getTotalTeamMembers(api, onResponse) {
  axios.get(api + '/teammembers/')
    .then(res => {
      onResponse(res.data.length);
    })
    .catch(err => {
      console.error(err)
    });
}

// Invokes callback with total Skill records in the api backend as param.
function getTotalSkills(api, onResponse) {
  axios.get(api + '/skills/')
    .then(res => {
      onResponse(res.data.length);
    })
    .catch(err => {
      console.error(err)
    });
}

... and I will need to create more, similar to these. The function they perform could likely be used in other components in the future. They could also be made even more generic, perhaps invoke a callback once for each object in the response, say.

Thoughts?

solkaz commented 7 years ago

I do this pattern on my projects, i.e. to separate "utility" functions into a separate file. I think it would help with making them more generic, and thus usable by other components/functions later on. I would thus agree with making a utilities file.

thebho commented 7 years ago

I would hold off moving the axios calls to a shared file until they are actually used in multiple places. I could see needing to call axios.get(api + '/skills/' when adding a tmskill but I'm not sure that we will handle the requests and errors the exact same way. If we get to that point and we are implementing it the same, finding a way to abstract it will make more sense.

Hopding commented 7 years ago

We probably won't often handle the API responses the exact same way, but the idea would be to make the generic networking functions invoke callbacks. E.g. forEachTeamMember(api, teamMember => {/* stuff */}) or forAllTeamMembers(/* ... */), etc...

Hopding commented 7 years ago

You could also pass an error callback.