'Typescript setState and return issue

In the following code:

1 export const useFetchErrors = (project_scan_id: number) => {
2     //const [errors, setErrors] = useState<Array<string>>([]);
3     const [isErrorsFetchComplete, setIsErrorsFetchComplete] = useState<boolean>(false);
4     const {enqueueSnackbar, } = useSnackbar();
5     const [num, setnum] = useState<number>(0)
6     let string_project_scan_id: string | null = String(project_scan_id)
7     let errorsArray: string[] = ['Apple', 'Orange', 'Banana'];
8     let t = true;
9     let one = 1
10    setnum(one)
11    console.log(num)
12    return {errorsArray, t}

On line 11 I'm trying to set the state of num (defined on line 5 to initially be 0) to 1, but when I console.log num on line 11 it's still 0. Then, in returning errorsArray and t on line 12 to some values in my other file which contains this code:

1 const {errors, errorsLoaded} = useFetchErrors(location.state.project_scan_id)
2 console.log(errors)

I get that the errors array is undefined on line 2, even though the string array errorsArray: string[] = ['Apple', 'Orange', 'Banana']; is supposed to be returned to it. How can I solve these issues?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source