I tried to put POST by AXIOS function inside another function to reuse it multiple times. but unfortunately It doesn't work as I expected (which was working using FETCH),
AXIOS CALL JS:
export async function post(apiRoute, body) {
try {
body = JSON.stringify(body);
axios.post(apiRoute, body, httpOptions)
.then((res)=>{
console.log(res.data); // I have data here
return res.data;
});
}
catch (err) {
console.log(err);
return err;
}
}
And the caller is:
async DoLogin(userName, password) {
var data = await post(url,{ // post is axios method defined above in another file
UserName: userName,
Password: password
});
return data; // I have nothing here
}
And the problem is I got undefined in DoLogin but got data inside POST method, It seems the problem is related to timing, axions returns a promise which is not possible to read in DoLogin, how I can do this? I did this via FETCH and it works perfectly.
try using async-await in this way.
export async function post(apiRoute, body) {
try {
const response = await axios.post(apiRoute, body, httpOptions)
return response.data;
}
catch (err) {
return err;
}
}
Related
err.response.data giving back the data I am looking for !!
Status code 302
The data is captured in the catch block instead of try block
This is the reudx slice code
export const getAllProject = async (dispatch) => {
try {
console.log("before");
const res = await apiLink.get(`/getAllProjects`);
console.log(res.data);
console.log("after");
dispatch(getAllProjectSuccess(res.data));
} catch (error) {
console.log(error.response.data);
// toast.error(error.response?.data.message);
}
};
The API is calling and the data is also coming.
I inspected the network tab
And also working in postman
But after the await, the code is not running.
React router version 5 is used in this project.
this is the proof of API calling
and
using axios interceptor like this
apiLink.interceptors.request.use(
async (config) => {
const TOKEN = JSON.parse(localStorage.getItem("accessToken"));
config.headers["authorization"] = "Bearer " + TOKEN;
return config;
},
(error) => {
return Promise.reject(error);
}
);
apiLink.interceptors.response.use(
function (response) {
return response;
},
function (err) {
if (err.response?.status === 500) {
userLogout();
}
return Promise.reject(err);
}
);
export default apiLink;
Edited:
err.response.data giving back the data I am looking for !!
I just log that and the status code of receiving the data is 302 .
What I want to do :
I send the GET request through axios
I open a local Json file with fs.readfile
I process the data and return it
I want to display the data when it return with res.json
what actually happened
I send the GET request through axios
I open a local Json file with fs.readfile
They return the data before fs.readfile finished so it's undefined or blank
This one I put on the frontend and the controller
//frontend
const fetchRewards = async()=>{
let link ="/api/reward";
const {data} = await axios.get(link);
console.log(data); **// this one logging undefined**
}
// on controller
async getRewardsById(req,res,next) {
try {
const result = await rewardService.getReward();
res.json(result);
} catch (error) {
next(error);
}
},
This is my service
const getReward = async () => {
fs.readFile("test.json", (err, inputData) => {
return {"name":"John", "age":30, "car":null};
}
console.log("done");
}
Seems to me like you are not returning anything from your service?
Try returning the fs.readFile.
export const deleteComment = (id) => {
console.log("id", id);
return async (dispatch) => {
try {
const response = await axios.delete(
`http://localhost:5000/comments/${id}`
);
console.log("response", response);
dispatch(actions.DeleteCommentAction(id));
} catch (err) {
console.log(err);
}
};
};
For some reasons, this code does not work. When i use this acton the console.log("id",id) is being executed, but console.log with response is not. I tested my route for deleting in Postman and everything works, does anyone know what is this happening?
Route for deleting, but as i said. It work, it some issue in React i guess:
router.delete("/:id", async (req, res) => {
const id = req.params.id;
try {
Comment.findByIdAndDelete(id, function (error, response) {
if (error) {
return res.send(error);
}
console.log(response);
return res.send(response);
});
} catch (error) {
return res.send(error);
}
});
Have you inspected the network tab to see if the request was sent?
Can you share the component where you are invoking deleteComment?
And perhaps try to simplify and execute the deletion outside the deleteComment method, it might be you are not injecting the dispatch method into the anonymous function.
The cause could also related to redux. I guess you are not using a redux middleware to handle the asynchronous executions as you are waiting the deletion, which could be a possible scenario for the issue. And maybe you could consider adding one of those middlewares like reduxk-thunk or redux-saga for example.
I actually forgot to add:
const mapDispatchToProps = {
deleteComment,
};
I want to achieve the following using React-jsx:
In one file, I have a function that makes a database request and returns some data. In another file, I want to call this function and then process the data. I want to handle this operation preferably using async/await as I have seen it should be possible to do, but I am not against a promise-based solution. Here is what I did:
export async function getData() {
try {
await request
.get(url, (err, res) => {
console.log('1', res.body);
return res.body;
}
} catch(e) {
return e;
}
}
And in the second file, where I call getData():
import { getData } from './path';
async formatData() {
try {
const data = await getData();
// some formatting
console.log('2', data);
} catch(e) {
return e;
}
}
And here is the result I get in the console:
> '2' undefined
suggesting that await hasn't worked. What I am missing?
I'm using axios in my react/redux application and when I get errors like 401, 404, etc I currently have to deal with them for each action function when I make the calls to axios. I have a axios_config.js where I've wrapped the axios calls with some common idioms. For example:
// need to move this to app config
const BASE_URL = 'http://localhost:8080/api/';
function config() {
return {
headers: {'X-Token-Auth': localStorage.getItem('token')}
}
}
export function fetchData(url) {
return axios.get(`${BASE_URL}${url}`, config());
};
Where I'm struggling are the common errors like 401, 404, etc. Currently, I'm doing this:
export function fetchBrands() {
return function(dispatch) {
dispatch({type:FETCHING_BRANDS});
fetchData('brands')
.then(response => {
dispatch({
type: FETCH_BRANDS_SUCCESS,
payload: response
});
})
.catch(err => {
// deal with errors
});
}
}
But in the catch block, I don't want to have to deal with 401, 404 etc every single time. So I need to be able to deal with those on a more global scale but still have the ability to handle specific errors to the request like server side validation errors for example.
You can use response interceptors as documents in axios documentation.
axios.interceptors.response.use(undefined, function (error) {
if(error.response.status === 401) {
ipcRenderer.send('response-unauthenticated');
return Promise.reject(error);
}
});
other thread with same discussion
You can try to write a function that accepts a function and returns the function with a catch attached. You can even pass an optional secondary argument to execute local catch logic.
This could then be moved to a single file and you can always modify it there.
export function fetchBrand(id) {
return function (dispatch) {
wrapCatch(
fetchData(`brands/${id}`)
.then(response => {
dispatch({
type: FETCH_BRAND_SUCCESS,
payload: response
});
}),
function (err) {
// deal with errors
}
);
}
}
export function wrapCatch(f, localErrors) {
return f.catch(err => {
// deal with errors
localErrors();
});
}
Hope this helps.