简体   繁体   中英

Importing functions using Typescript

TLDR - what's the difference between these imports in ReactJs using Typescript:

setState1: (numbers: number[]) => void,
setState2: Function

Hi peeps, I've recently came across weird(for me) behaviour of importing functions using Typescript on React. To explain it better I'll just put sample code:

const FuncComp: React.FC = () => {
   const [state1, setState1] = useState<number[]>([]);
   const [state2, setState2] = useState<number[]>([]);

   const handleSettingState1 = () => {
       console.log("state1-",state1);
       setState1([...state1, 1]);
   }
   console.log("state1-",state1);

   const handleSettingState2 = () => {
       console.log("state2-",state2);
       setState1([...state2, 2]);
   }
   console.log("state2-",state2);

   const saveChanges = () => {
       saveHandler(
          saveFunc,
          setState1,
          setState2
       )
   }
....
}

both handleSettingState1 and handleSettingState2 are functions passed to and set from child components, saveChanges is onClick function of button inside FuncComp and saveHandler is imported from helper file and it looks like this:

export const saveHandler = (
    saveFunc: GqlMutationType,
    setState1: (numbers: number[]) => void,
    setState2: Function
) => {
    saveFunc()
        .then(() => {
            setState1([]);
            setState2([]);
        })
        .catch((err: AxiosError) => {
            console.log(err);
        });
};

As you can see setState1 and setState2 are imported differently. Now the problem is that when I set both states through handlers -> perform save(it should clear both arrays in then callback) -> set another value, state1 will be empty both inside and outside handleSettingState1 scope, while state2 will have old value inside handleSettingState2 but empty inside the scope of the class.

I skipped implementation of handleSettingState2 and handleSettingState2 inside child component because I thought it's irrelevant but if it affects I can provide it too.

You can update the save handler like so.

export const saveHandler = (
    saveFunc: GqlMutationType,
    cb: (data: any) => void
) => {
    saveFunc()
        .then(data => cb(data))
        .catch((err: AxiosError) => {
            console.log(err);
        });
};

Importing and calling the function

import { saveHandler } from './filename';
...
...
function saveFn() {}

saveHandler(saveFn, (data) => {
   setState([...data]);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM