Technologies:
Tolerim
15 days ago
The API call functions correctly in Postman, but when triggered from the front end, it is returned as "undefined".
The server-side request appears to be successful, as evidenced by the Postman response containing the expected values. The backend code for this can be found below:
const showStats = async (req, res) => {
let stats = await Job.aggregate([
{ $match: { createdBy: new mongoose.Types.ObjectId(req.user.userId) } },
{ $group: { _id: '$status', count: {$sum:1 }}}
]);
stats = stats.reduce((acc, curr) => {
const { _id: title, count } = curr;
acc[title] = count;
return acc;
}, {})
const defaultStats = {
pending: stats.pending || 0,
interview: stats.interview || 0,
declined: stats.declined || 0,
};
let monthlyApplications = [];
res.status(StatusCodes.OK).json({ defaultStats, monthlyApplications });
};
Despite the successful server-side response, the React frontend fails to receive a response, as it returns as undefined. Axios was used to make an authorized fetch request, as shown in the following code:
const AppProvider = ({children}) =>{
const [state, dispatch] = useReducer(reducer, initialState)
//axios
const authFetch = axios.create({
baseURL: '/api/v1',
})
authFetch.interceptors.request.use(
(config) => {
config.headers['Authorization'] = `Bearer ${state.token}`;
return config;
},
(error) => {
return Promise.reject(error);
}
);
authFetch.interceptors.response.use(
(response) => {
return response;
},
(error) => {
console.log(error.response)
if (error.response.status === 401) {
logoutUser();
}
return Promise.reject(error);
}
);
The issue seems to originate from the "showStats" function, which happens to be the specific point of interest. The code block below shows the "showStats" function:
const showStats = async () => {
dispatch({ type: SHOWSTATSBEGIN });
try {
const {data} = await authFetch('/jobs/stats')
console.log(data)
dispatch({
type: SHOWSTATSSUCCESS,
payload: {
stats: data.defaultStats,
monthlyApplications: data.monthlyApplications,
}
})
} catch (error) {
console.log(error.response)
//logoutUser()
}
}
Lastly, here's the "Stats" component where the "showStats" function is called:
import { useEffect } from "react"
import { useAppContext } from "../../context/AppContext"
import { StatsContainer, Loading, ChartsContainer } from "../../components"
const Stats = () => {
const { showStats, isLoading, monthlyApplications } = useAppContext()
useEffect(() => {
showStats()
}, [])
if (isLoading) {
return <Loading center />
}
return (
<>
<StatsContainer />
{monthlyApplications.length > 0 && <ChartsContainer />}
</>
)
}
export default Stats
Despite multiple attempts of troubleshooting, the issue remains unclear. Any assistance would be greatly appreciated.Answers(1)
Tolerim
15 days ago
Verified Answer
It looks like the issue may be with the way the showStats function is being called in the Stats component. The function is being called without passing in the req and res parameters that are expected by the backend API route.
To fix this, you will need to modify the showStats function to take in these parameters and pass them in when calling the function from the Stats component:
dispatch({ type: SHOW_STATS_BEGIN });
try {
const { data } = await authFetch('/jobs/stats', { params: { req, res } });
console.log(data);
dispatch({
type: SHOW_STATS_SUCCESS,
payload: {
stats: data.defaultStats,
monthlyApplications: data.monthlyApplications,
},
});
} catch (error) {
console.log(error.response);
//logoutUser()
}
};
And then modify the Stats component to pass in the req and res parameters when calling the showStats function:
showStats(req, res);
}, []);
Keep in mind that you will need to define the req and res variables in the Stats component or pass them in from a parent component.