UseEffect not returning response onMount - reactjs

I am running a test on page load and refresh. It is working well but the test is returning 0;
below is my code;
useEffect(() => {
setLoading(true);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
} else {
setError("Your browser doesn't support geolocation");
}
const fetchLocations = async () => {
if(currentPos.latitude!==undefined && currentPos.longitude!==undefined) {
try {
const response = await instance
.get("/explore", {
params: {
ll: `${currentPos.latitude},${currentPos.longitude}`
}
})
console.log(response.data.response.groups[0].items);
setLocations(response.data.response.groups[0].items);
setError('')
setLoading(false)
} catch (error) {
setError('Error getting data');
setLoading(false)
}
}
}
fetchLocations()
}, [currentPos.latitude, currentPos.longitude]);
and my test:
What is happening here is on first mount loading... is available. On fetching data from the API is expected toHaveBeenCalledTimes to be 1 instead of returning 0.
it("renders location venues on currentlocation ", async () => {
const {getByText, container} = render(<Venues />);
getByText('Loading...')
await axiosMock.get.mockResolvedValueOnce(() =>
Promise.resolve({ data: {response } })
)
expect(axiosMock.get).toHaveBeenCalledTimes(0)
await waitForElement(() =>
container,
expect(axiosMock.get).toHaveBeenCalledTimes(1)
);
});
How can I fix this test and make it work properly?

Related

How to make a PATCH request in ReactJS ? (with Nestjs)

nestjs controller.ts
#Patch(':id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
#Body('shippingAddr') addrShipping: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling, addrShipping);
return null;
}
nestjs service.ts
async updateProduct(
addressId: string,
addrBilling: boolean,
addrShipping: boolean,
) {
const updatedProduct = await this.findAddress(addressId);
if (addrBilling) {
updatedProduct.billingAddr = addrBilling;
}
if (addrShipping) {
updatedProduct.shippingAddr = addrShipping;
}
updatedProduct.save();
}
there is no problem here. I can patch in localhost:8000/address/addressid in postman and change billingAddr to true or false.the backend is working properly.
how can i call react with axios?
page.js
const ChangeBillingAddress = async (param,param2) => {
try {
await authService.setBilling(param,param2).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
return....
<Button size='sm' variant={data.billingAddr === true ? ("outline-secondary") : ("info")} onClick={() => ChangeBillingAddress (data._id,data.billingAddr)}>
auth.service.js
const setBilling = async (param,param2) => {
let adressid = `${param}`;
const url = `http://localhost:8001/address/`+ adressid ;
return axios.patch(url,param, param2).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}
I have to make sure the parameters are the billlingddress field and change it to true.
I can't make any changes when react button click
Since patch method is working fine in postman, and server is also working fine, here's a tip for frontend debugging
Hard code url id and replace param with hard coded values too:
const setBilling = async (param,param2) => {
// let adressid = `${param}`;
const url = `http://localhost:8001/address/123`; // hard code a addressid
return axios.patch(url,param, param2).then((response) => { // hard code params too
console.log(response); // see console result
if (response.data.token) {
// localStorage.setItem("user", JSON.stringify(response.data));
}
// return response.data;
})
}
now it worked correctly
#Patch('/:id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling);
return null;
}
const ChangeBillingAddress = async (param) => {
try {
await authService.setBilling(param,true).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
const setBilling= async (param,param2) => {
let id = `${param}`;
const url = `http://localhost:8001/address/`+ id;
return axios.patch(url,{billingAddr: param2}).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}

Can't fetch data with Axios and React, getting an Promise and Undefined

I'm trying to fetch some data with Axios and React, But I'm having a problem resolving the promise and setting it on the state, that's weird.
Here is the Base:
export const fetchUserById = (username) => client.get(`/${username}`);
Here is the Call:
export const getUserById = async (username) => {
try {
const response = await api.fetchUserById(username);
const data = await response.data;
return data;
} catch (error) {
return error;
}
};
Here is in React:
const [user, setUser] = useState();
useEffect(() => {
const data = getUserById(params.username); // this gets the username and its working
setUser(data)
}, [])
useEffect(() => {
console.log("this is user: ", user)
}, [user])
If I console log user, I get undefined, If I console log data i get a promise.
getUserById is declared async so it implicitly returns a Promise that callers should either await or use a Promise chain on.
useEffect(() => {
const data = getUserById(params.username);
setUser(data); // <-- logs only the returned Promise object!
}, [])
async/await
useEffect(() => {
const getUser = async () => {
try {
const data = await getUserById(params.username);
setUser(data);
} catch(error) {
// handle error, log, etc...
}
};
getUser();
}, []);
Promise chain
useEffect(() => {
getUserById(params.username)
.then(data => {
setUser(data);
})
.catch(error => {
// handle error, log, etc...
});
};
}, []);
Or you could as well do:
useEffect(() => {
// fetch data
(async () => {
try {
const data = await getUserById(params.username);
// set state
setUser(data)
} catch(error) {
// handle error, log, etc...
// set init state
setUser(null)
}
})();
}, []);

How to fetch data from MongoDB?

I am trying to use Express + MongoDB building React app.
I was able to post some documents to MongoDB. Currently, I'm trying to figure out how to print fetched data to the screen.
I have these routes:
router.post('/totalbalance', (request, response) => {
const totalBalance = new TotalBalanceModelTemplate({
totalBalance:request.body.totalBalance,
});
totalBalance.save()
.then(data => {
response.json(data);
})
.catch(error => {
response.json(error);
});
});
router.get('/totalbalance', (request, response) => {
TotalBalanceModelTemplate.find(request.body.totalBalance, (error, data) => {
if (error) {
return error
} else {
response.json(data[0])
}
})
});
This is axios request:
useEffect(() => {
const resp = axios.get('http://localhost:4000/app/totalbalance');
console.log(resp);
}, []);
It returns a promise that has a parameter data which equals to object value which is the first value in the array
data: {_
id: "60c48b4ec60919553d92319f",
totalBalance: 5555,
__v: 0
}
and prints it out to the console.
How can I print out to the console the value totalBalance instead of whole promise?
By the way, sometime the array of data is empty (there are no documents in the DB), how should i handle these cases as well?
Thanks!
First of all, Axios GET method does not have any request body. But you are trying to use it in the MongoDB query. - "TotalBalanceModelTemplate.find(request.body.totalBalance, (error, data) => {".
The find query should be object {}. If require pass on conditions to it.
First point, to print only "totalBalance" output. Use, console.log(resp.totalBalance);
Second point, to handle records length, have a if else condition,
if (error) {
return error
} else if (data.length) {
return response.send("No records found")
} else {
response.json(data[0])
}
Try this :
Routes
router.post("/totalbalance", async (req, res) => {
try {
const totalBalance = new TotalBalanceModelTemplate({
totalBalance: req.body.totalBalance,
})
await totalBalance.save();
res.json(totalBalance)
} catch (error) {
res.status(400).json({
message: error.message
})
}
})
router.get("/totalbalance", async (req, res) => {
try {
const totalBalances = await TotalBalanceModelTemplate.find();
res.json(totalBalances)
} catch (error) {
res.status(400).json({
message: error.message
})
}
})
App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function App() {
const [data, setData] = useState([]);
const getData = async () => {
try {
const response = await axios.get('http://localhost:4000/app/totalbalance');
await setData(response);
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getData();
}, []);
return (
<div>
{data <= 0 ? (
<div className="empty">
<p>No data!</p>
</div>
) : (
data.map((d) => (
<ul key={d.id}>
<li>{d.totalBalance}</li>
</ul>
))
)}
</div>
);
}

How do I get the HTTP response code from a successful React query?

How do I get the status code from a successful React query?
This is my custom hook:
const validateIban = async (accountId, encodedIban) => {
await axios
.post(`${CUSTOMER_PORTAL_API}/policy/accounts/${accountId}/iban/${encodedIban}`)
};
export function useValidateIban(accountId) {
return useMutation(encodedIban => validateIban(accountId, encodedIban));
}
And this is where I use the hook with mutate:
const validateIbanQuery = useValidateIban(accountId)
validateIbanQuery.mutate(encodeURIComponent(iban), {
onSuccess: () => {
******HERE I WANT THE STATUS CODE (204, 202 e.g.)******
},
onError: (error) => {
if (error.response.status === 400) {
....
}
if (error.response.status === 403) {
....
}
}
})
The first parameter of the onSuccess callback is the AxiosResponse:
axios.post("/api/data", { text }).then(response => {
console.log(response.status)
return response; // this response will be passed as the first parameter of onSuccess
});
onSuccess: (data) => {
console.log(data.status);
},
Live Demo

Re-calling an async function in useEffect inside of another async function after a failed api fetching request

This is a bit tricky to explain, but here is what I'm doing:
Trying to get json data from an async function called getJsonData() until data is fetched.
After getting the data correctly, I want to get another set of json data from getOtherJsonData()
The following code gets me the first set of data (getJsonData) correctly even after X failures. (if any)
It doens't however get the second set of data (getOtherJsonData) all the time as an error could occur. I want to keep re-execution the bloc of code marked below until the second set of data is returned correctly.
...
import React, {useState, useEffect} from 'react';
import {getJsonData} from './getJsonData';
imoport {getOtherJsonData} from './getOtherJsonData';
const myApp = () => {
const [errorFetchedChecker, setErrorFetchedChecker] = useState(false);
const [isLoading,setIsLoading] = useState(true);
const [data,setData] = useState(null);
const updateState = jsonData => {
setIsloading(false);
setData(jsonData);
};
useEffect(() => {
getJsonData().then(
data => {
updateState(data);
// This is the bloc I want to keep re-executing
//
getOtherJsonData(data.title).then(
otherData => {
updateOtherState(otherData);
console.log("Updated with no error);
},
otherError => {
console.log("Error, try getOtherJsonData again ?");
console.log("Can't try to refresh, no errorFetchedChecker for me :/ ");
}
//
// Until It doesn't return an error
},
error => {
console.log('Error fetching, re-trying to fetch thanks to errorFetchedChecker');
setErrorFetchedChecker(c => !c);
},
);
}, [errorFetchedChecker]);
return (
<View>
<Text>{state.data.title}</Text>
<Text>{data.data.completed}</Text>
</View>
);
}
Here's getJsonData() and getOtherJsonData()
export async function getJsonData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let responseJson = await response.json();
return responseJson;
} catch (error) {
throw error;
// Should I just throw the error here ?
}
}
export async function getOtherJsonData(oldData) {
try {
let response = await fetch(`https://someOtherApilink/${oldData}`);
let responseJson = await response.json();
return responseJson;
} catch (error) {
throw error;
// Should I just throw the error here also ?
}
}
This is my other question which explains how to re-execute the first getJsonData() in case of failure.
Below is something I tried but gave me error about unhandled promises:
const subFunction(myTitle) => {
getOtherJsonData(myTitle).then(
otherData => {
updateOtherState(otherData);
console.log("Updated with no error);
},
otherError => {
console.log("Error, try getOtherJsonData again!");
subFunction(myTitle); //Gives Unhandled promise warning and no result
}
}
useEffect(() => {
getJsonData().then(
data => {
updateState(data);
// This is the bloc I want to keep re-executing
//
subFunction(data.title);
//
// Until It doesn't return an error
},
error => {
console.log('Error fetching, re-trying to fetch thanks to errorFetchedChecker');
setErrorFetchedChecker(c => !c);
},
);
}, [errorFetchedChecker]);
Note: Feel free to rephrase the title in any way, shape or form.
You can try to separate these two functions with using two useEffect, because now you'll have to repeat first request in case of second fail. Something like this:
useEffect(() => {
getJsonData().then(
data => {
updateState(data);
},
error => {
console.log('Error fetching, re-trying to fetch thanks to errorFetchedChecker');
setErrorFetchedChecker(c => !c);
},
);
}, [errorFetchedChecker]);
useEffect(() => {
// prevent request if there's no data
if (data) {
getOtherJsonData(data.title).then(
otherData => {
updateOtherState(otherData);
console.log("Updated with no error);
},
otherError => {
console.log("Error, try getOtherJsonData again ?");
console.log("Can't try to refresh, no errorFetchedChecker for me :/ ");
// you'll have to create one more state for that
setOtherErrorFetchedChecker(c => !c);
}
}
}, [data, otherErrorFetchedChecker])

Resources