Home > other >  How to wait result of a function in React?
How to wait result of a function in React?

Time:06-16

I am trying to fetch info from an endpoint and assign it to a local variable. The problem is that the info is fetched successfully and when I put console.log(resp.data) it is printed, so I assign it to the faculties, but in the following line faculties is an empty array. I tried async/await -> I defined showOptions function as async and awaited facultiesService.getAllFaculties(), but the problem was not solved and some other errors occured. How can I solve this issue?

 const showOptions = () => {
            let faculties = [];
            facultiesService.getAllFaculties()
                .then(async (resp) => {
                    faculties = await resp.data;
                })
                .catch(e => console.log(e));
        console.log(faculties)
        return faculties.map(faculty => {
            return <option
                key={faculty.id}
                value={faculty.id}
            >{faculty.name}
            </option>
        });
    }

    const showFacultySelect = () => {

        return (
            <Form.Select aria-label="Default select example">
                {showOptions()}
            </Form.Select>
        )
    }

CodePudding user response:

You are using async/await in wrong way. They are meant for sequential code rather than callbacks. You should be doing something like this:

const showOptions = async () => {
            let result = await facultiesService.getAllFaculties();
            let faculties = await resp.data;
           console.log(faculties)
        return faculties.map(faculty => {
            return <option
                key={faculty.id}
                value={faculty.id}
            >{faculty.name}
            </option>
        });
    }
  • Related