Home > Net >  useEffect and fetching data
useEffect and fetching data

Time:05-11

so I'm trying to fetch some data from the backend to determine the route the member will reach when he/she logins.

I'm using useEffect to do so but I'm failing to fetch the data before the rendering of the page.

useEffect(() => {
    if (primaryRole === 'asap-dept-member') {
        apiService.ApplicationService.getMemberApplication(asapUser.id).then(response => {
            response
                .filter(application => application.applicant.user.id === asapUser.id)
                .forEach(res => {
                    setArray(res);
                    setApplication(res.id);
                });
        });
    }
}, [asapUser.id, primaryRole]);

if (array !== null && primaryRole === 'asap-dept-member') {
    console.log(application);
    initialRoute = routesMetadataForRole[2]?.path.replace(':id', application);
} else {
    initialRoute = routesMetadataForRole[0]?.path;
}

this is the API call

static getMemberApplication() {
    return $axios.get(`application/member/`, { headers: authHeader() }).then(response => response.data);
}

and the problem I'm trying to solve is that I'm getting undefined before getting the application number.

enter image description here

any suggestions on solving it? I know that I need to use an async function but every time I try it I'm getting the same result.

CodePudding user response:

Axios will return a promise. You have to listen to the promise and then execute the setstate. You can read more about the promise here. I personally use async/await(suger coating for promises).

    const fetchData = async () => {
    if (primaryRole === 'asap-dept-member') {
            const data = await apiService.ApplicationService.getMemberApplication(asapUser.id);
            // now compute on the data...
             data.filter.....
             .forEach.....
            });
        }
    }, [asapUser.id, primaryRole]);
    
    if (array !== null && primaryRole === 'asap-dept-member') {
        console.log(application);
        initialRoute = routesMetadataForRole[2]?.path.replace(':id', application);
    } else {
        initialRoute = routesMetadataForRole[0]?.path;
    }
    };

    useEffect(() => {
        fetchData();
    })

CodePudding user response:

you should be using an async function try the following

useEffect(() => {
    async function fetchApi() {
      return apiService.ApplicationService.getMemberApplication(asapUser.id);
    }
    fetchApi().then((response) => {
       response
                .filter(application => application.applicant.user.id === asapUser.id)
                .forEach(res => {
                    setArray(res);
                    setApplication(res.id);
                });
    });
  }, [asapUser.id, primaryRole])

  • Related