Getting Promise instead of actuall value in React - reactjs

Hi I'm using axios to call API, Now the problem is Whenever I call API it's returning promise with Array as a result instead of actual value.
Here is the code:
export const GetResults=async(arrays)=>{debugger
let res=await arrays?.map(async (i) => {
const response= await callAPI(i);
return response
})
return res
}
import {GetResults} from'../../someFun'
const callMe=async()=>{debugger
const res= await GetResults(["1","2","3")
console.log( res)========/Promise
}
const callAPI = (
id?: string,
): Promise<void> => {
const params = {
id: id,
};
return api
.get<>('api end point', { params })
.then(({ data }) => data)
.catch((err) => {
return err;
});
};
How to get actual return value instead of promise

You can use Promise.all to return all the resolved promises:
async function callAPI(i) {
return `API response: ${i}`;
}
async function getResults(arrays) {
const apiCalls = arrays?.map(async (i) => callAPI(i));
return Promise.all(apiCalls);
}
async function callMe() {
const res = await getResults(["1", "2", "3"]);
console.log(res);
}
callMe();

May be const res= await GetResults(["1","2","3"]).toPromise() will work.

Related

React & Fetch async/await... Why I'm receiving a promise?

I'm having some troubles about react, fetch and async/await.
I have this code as a fetch wrapper:
export const fetcher = (url, options = null) => {
const handle401Response = error => {
throw error;
}
const isResponseValid = response => {
if (!response.ok)
throw response;
else
return response.json();
}
return fetch(url, { ...options, credentials: 'include' })
.then(isResponseValid)
.catch(handle401Response);
}
Then I define some API calls functions like:
export const getGroups = (id = null) => {
return fetcher(`${API_GROUP_URL}${id !== null ? `?id=${id}` : ''}`);
}
And then I try to use it like:
export function SomeComponent(props) {
const groups = async () => {
try {
const ret = await getGroups();
return ret;
} catch (err) {
console.log(err);
}
};
console.log(groups());
return <h1>Component</h1>
}
The result in console is: Promise{}.
I have read docs about async/await but can't understand why await is not waiting for promise to end.
Thanks in advance!
export function SomeComponent(props) {
const [data, setData] = useState()
const groups = async () => {
};
useEffect(() => {
const fetchData = async () => {
try {
const ret = await getGroups();
// process and set data accordingly
setData(ret)
} catch (err) {
console.log(err);
}
}
// fetch data inside useEffect
fetchData()
}, [])
// console.log(groups());
return <h1>Component {data?.prop}</h1>
}
Hope this gives you an idea on how to fetch in a functional component
Async functions always return a promise. The time when you call that function it will give you back a promise instantly. You have used await inside the function and it is waiting for getGroup promise.
In normal javascript function console.log(await) this will fix the issue but in react you have to do it inside a another function because you cant make react components async (at least not in React 17 and below)

React how to wait for all axios to finish

I want to wait until all axios in useEffect are finished.
UseEffect:
useEffect(() => {
async function getHomePageContent() {
await HomePageServices.getSliderContent().then((response) => {
setSliderProduct(response.data);
});
await HomePageServices.getRecommendedProducts().then((response) => {
setRecommendedProducts(response.data);
});
await HomePageServices.getMostOrderProducts().then((response) => {
setMostOrderProducts(response.data);
});
await HomePageServices.getMostRatedProducts().then((response) => {
setMostRatedProducts(response.data);
});
}
getHomePageContent().catch((error) => {
console.log(error)
});
}, []);
Class:
class HomePageServices{
async getSliderContent(){
return await axios.get(baseURL+"/slider")
}
async getMostRatedProducts(){
return await axios.get(baseURL+"/mostRatedProducts")
}
async getMostOrderProducts(){
return await axios.get(baseURL+"/mostOrderProduct")
}
async getRecommendedProducts(){
return await axios.get(baseURL+"/recommendedProduct")
}
}
Can someone explain to me how to wait for all axios to end, and if one failed, how to find out which one it was?
Try using Promise.allSettled() which takes an iterable (e.g. array) of promises and resolves into array of results of each of them.
Results are represented as objects with status key, which can be rejected or fulfilled. The second key of the object is either value containing the resolved value, or reason in case promise was rejected.
Taking this, then your code in useEffect might be something like this:
useEffect(() => {
const getHomePageContent = async () => ({
const promises = [
HomePageServices.getSliderContent(),
HomePageServices.getRecommendedProducts(),
HomePageServices.getMostOrderProducts(),
HomePageServices.getMostRatedProducts()
];
const data = await Promise.allSettled(promises);
const [slider, recommended, mostordered, mostrated] = data;
// result for each of promise
console.log(slider); // { status: 'fulfilled', value: 123 }
console.log(recommended) // { status: 'rejected', reason: 'blah'}
});
getHomePageContent().catch((er) => console.log(er))
}, [])

axios returns promise instead of data

I am querying some data from IPFS using axios, the problem is that after calling the specific api the return value is a promisse from axios.
const getNFTDetail = async (url: string) => {
const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
try {
return await axios.get(urlIPF).then((res) => {
return res.data;
});
} catch (error) {
console.log(error);
}
};
response I get:
is there a way to wait until promisse has been resolved?, as you see I am already using async await on the function call.
just, decide if you use async / await or .then / .catch:
const getNFTDetail = async (url: any) => {
const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
const { data } = await axios.get(urlIPF);
return data;
};
or
const getNFTDetail = (url: any) => {
const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
axios.get(urlIPF).then(({data}) => {
// use your data here
}).catch((err)=>{
console.log(err);
};
};
When you fetch a request, no matter any http client you use, will then return a Promise.
Just use await to get a response from your request.
const response = await axios.get(your-url);
const json = await response.json();
To use typescript correctly, type the url a string: (url: string) instead of happy any type.

How to assign axios response to a constant and return the const with assigned value in React

The below mentioned code does not set the values to response constant and I am not able to return it.
export const calculateData= async ({
assetId,
mappings,
}: {
assetId: number;
mappings: MappingDIn[];
}) => {
const response = await axios.post<ClassModal>(
`/api/assets/${assetId}/calculateData`, mappings).then(response=>
{
console.log(response)}).catch(error=>{console.error(error)});
return response;
};
export const calculateData = async ({
assetId,
mappings,
}: {
assetId: number;
mappings: MappingDIn[];
}) => {
try {
const response = await axios.post<ClassModal>(`/api/assets/${assetId}/calculateData`, mappings);
return response;
} catch (error) {
console.error(error);
}
}
Async function will always return a Promise. If you return anything else, it will wrap it in a Promise object.
Either use async / await or use Promise (.then, .catch, .finally), but don't mix them together. You can achieve with both the same results, but some people see async / await as best practice.

React - How do I get fetched data outside of an async function?

I'm trying to get the data of "body" outside of the fetchUserData() function.
I just want to store it in an variable for later use.
Also tried modifying state, but didn't work either.
Thanks for your help :)
const [userData, setUserData] = useState();
async function fetchUserData () {
try {
const result = await fetch(`/usermanagement/getdocent`, {
method: "GET"
});
const body = await result.json();
//setUserData(body);
return(
body
)
} catch (err) {
console.log(err);
}
}
let userTestData
fetchUserData().then(data => {userTestData = data});
console.log(userTestData);
//console.log(userData);
Use useEffect
async function fetchUserData () {
try {
const result = await fetch(`/usermanagement/getdocent`, {
method: "GET"
})
return await result.json()
} catch (err) {
console.log(err)
return null
}
}
const FunctionalComponent = () => {
const [userData, setUserData] = useState()
useEffect(() => {
fetchUserData().then(data => {
data && setUserData(data)
})
}, []) // componentDidMount
return <div />
}
Ben Awad's awesome tutorial
Example:
it seems that you are making it more complicated than it should be. When you get the response i.e the resolved promise with the data inside the async function, just set the state and in the next render you should get the updated data.
Example:
const [userData, setUserData] = useState();
useEffect(() => {
const getResponse = async () => {
try {
const result = await fetch(`/usermanagement/getdocent`, {
method: "GET"
});
const body = await result.json();
setUserData(body);
} catch (err) {
console.log(err)
}
}
getResponse();
}, [])
console.log(userData);
return <div></div>
Assuming the you need to call the function only once define and call it inside a useEffect or 'componentDidMount'. For using async function inside useEffect we need to define another function and then call it.
When you do
let userTestData
// This line does not wait and next line is executed immediately before userTestData is set
fetchUserData().then(data => {userTestData = data});
console.log(userTestData);
// Try changing to
async someAsyncScope() {
const userTestData = await fetchUserData();
console.log(userTestData)
}
Example:
state = {
someKey: 'someInitialValue'
};
async myAsyncMethod() {
const myAsyncValue = await anotherAsyncMethod();
this.setState({ someKey: myAsyncValue });
}
/*
* Then in the template or where ever, use a state variable which you update when
* the promise resolves. When a state value is used, once the state is updated,
* it triggers as a re-render
*/
render() {
return <div>{this.state.someKey}</div>;
}
In your example you'd use setUserData instead of this.setState and userData instead of {this.state.someKey}

Categories

Resources