0

I have a method that uses Axios to connect to an API.

I need to use it twice in my app, but the only way I can figure out how to get it to work is by duplicating a bunch of code as you see below.

I tried calling updateHealthData in my if statement, but it says it's not defined.

So the only way I figured out to do it was to call the axios statement twice.

But this seems like it's duplicating the code too much.

Is there anyway to define it so that I don't have to do it like this?

Thanks!

const App = ({ healthId, healthTerms }) => {

    var savedTerms = localStorage.getItem(healthId);

    if (healthTerms !== savedTerms) {
        const request = axios.put(`/api/healthPortal/${healthId}/healthTerms`, JSON.stringify(savedTerms), {
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }


    const updateHealthData = (i) => {
        localStorage.setItem(healthId, i);
        const request = axios.put(`/api/healthPortal/${healthId}/healthTerms`, JSON.stringify(i), {
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }
    return ( <TermManager onChange={updateHealthData} />   )
}
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185
  • 1
    put the function above the code where you are using it, or declare it with normal function declaration (not arrow declaration) –  Jun 10 '21 at 19:33
  • @EliteDaMyth thanks! I know this sounds naïve, but isn't arrow functions how we should write modern functions in React? thank you – SkyeBoniwell Jun 10 '21 at 19:36
  • 3
    @SkyeBoniwell No, it's not. Arrow functions are not "more modern" - they were introduced later, but they simply *supplement* normal function declarations with their [different features](https://stackoverflow.com/q/34361379/1048572). See also [this](https://stackoverflow.com/questions/38479859/what-are-the-advantages-disadvantages-for-creating-a-top-level-function-in-es6-w) and [that](https://stackoverflow.com/q/22939130/1048572). – Bergi Jun 10 '21 at 19:40

0 Answers0