This question already has answers here:
ES6 Import some functions as a object
(3 answers)
Closed 11 months ago.
There are 3 functions imported:
import { searchShip, searchLcl, searchFcl } from "services/logisticsService";
searchData = {
currentPort: currentPort,
destinationPort: destinationPort,
date: readyTOLoad,
type: containerType, // containerType is geting 1 value among this (ship,lcl,fcl)
}
Here I want to call one of those function based on that containerType value. For example:
If I get type value as ship then it should be
searchShip(searchData).then((response) => {
console.log(response)
})
If I get type value as lcl then it should be
searchLcl(searchData).then((response) => {
console.log(response)
})
If I get type value as fcl then it should be
searchFcl(searchData).then((response) => {
console.log(response)
})
Is there any good way to call that search function on that type condition without if else statement because inside it there is very lengthy process to handle response.
Yes, you can define an object that has a {[key]: function} structure.
const handlersByType = {
ship: searchShip,
lcl: searchLcl,
fcl: searchFcl.
};
handlersByType[type](searchData).then((response) => {
console.log(response)
})
Related
This question already has an answer here:
How to resolve pending promises within map returning an object?
(1 answer)
Closed 10 months ago.
i have a array that contains a object with two values, like this:
[
{
brand: app1,
url: https://myhost.com/api
},
{
brand: app2,
url: https://otherapi.com/api
}
]
I'am using axios.all to made a get request over all urls, and I iterate it with a map, like this:
const getData= axios.all(stuffData.map((item) => axios.get(item.url)))
.then(res => console.log(res.data)
The thing is, how can I pass the second param in the array when i make the map to interate all axios requests? I also need pass the key "brand".
Thanks
Use this:
Promise.all(stuffData.map(async (item) => ({
data: await axios.get(item.url).data,
brand: item.brand
}))).then((data) => {
data.forEach(item=> console.log(item))
})
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed last year.
I have been trying to create a table from an array of objects. I'm able to console the data inside the async function. But I couldn't console it outside.
My code :
useEffect(() => {
listingCampaignsModels()
}, []);
async function listingCampaignsModels() {
const apiData = await DataStore.query(Campaign);
console.log(apiData);
console.log(typeof(apiData));
return apiData;
};
When I tried to console apiData outside, it returns apiData is not defined error.
The data looks like this :
[Model, Model, Model, Model, Model, Model]
Each Model looks like :
-> 1: Model {id: 'c40d6b22-840f-467a-909c-7b2b19960ffb', campaignOwner: 'eumagnas', campaignName: "mollitlab", startDate: "2022/08/15", endDate: "2022/10/25", expectedRevenue: 25, budgetedCost: 27, actualCost: 28}
I want loop through all the Models and create a table as :
Campaign Owner
Campaign Name
Start Date
End Date
Expected Revenue
Budgeted Cost
Actual Cost
eumagnas
mollitlab
2022/08/15
2022/10/25
25
27
28
You need to use useState() hook to save the data as campaign state.
const [campaigns, setCampaigns] = useState([]);
useEffect(() => {
listingCampaignsModels()
}, []);
async function listingCampaignsModels() {
const apiData = await DataStore.query(Campaign);
console.log(apiData);
setCampaigns(apiData);
};
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed last year.
In vuejs3 app I want to use common method, so I put it into mixin resources/js/appMixin.js as :
export default {
methods: {
async getBlockPage(page_slug) {
const response = await axios.post('/get_block_page', {slug: this.page_slug})
console.log('response.data.page::')
console.log(response.data.page) // In the browser console I see this valid page object returned
return response.data.page;
}, // getBlockPage() {
but calling this method in vue file :
mounted() {
this.about= this.getBlockPage("about");
console.log('AFTER this.about::') // I DO NOT this output
console.log(this.about)
},
and outputting about var I see
"[object Promise]"
Which is the valid way?
That question seems a bit specific then provided link, as method is inside of mixin...
Thanks in advance!
Yes sure, getBlockPage is an async function, always return Promise.
async mounted() {
this.about= await this.getBlockPage("about");
console.log(this.about)
},
or
mounted(){
this.getBlockPage("about")
.then(result => {
console.log(result);
)
.catch(error => {
//error handler
});
}
You can learn more here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Async / await is just a syntaxic sugar for define Promise behavior on your function
This question already has an answer here:
ES6 deep nested object destructuring
(1 answer)
Closed 1 year ago.
I have an Apollo query:
const { error, loading, data: user } = useQuery(resolvers.queries.ReturnUser, {
variables: { userId: parseInt(id) },
});
The data object returned from the query has another object called returnUser. So the actual object is:
data: {
returnUser: {
name: 'Some Name'
}
}
In my JSX I want to output the data:
return (
<div>
{ user ?
<p>Profile {user.returnUser.name}</p> :
<div>User not found</div> }
</div>
);
As you can see I need to access the returnUser object on the user object to get the actual user data. This is not great. Is there any way to destructure the data object from the useQuery so I can assign the nested object to user?
//edit: While this looks like a duplicate question, the answer is different due to the async nature of useQuery. If you don't set a default value you'll get an error.
Got the answer thanks to #Pilchard:
const {error, loading, data: {returnUser: user} = {}} = useQuery(resolvers.queries.ReturnUser, {
variables: {userId: parseInt(id)},
});
You can follow the same nesting while deconstructing the data.
e.g.
const data = {
anotherLevel: {
returnUser: {
name: 'Some Name'
}
}
}
const { anotherLevel: {returnUser: { name }}} = data;
console.log(name); // prints Some Name
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 2 years ago.
case 'ADD_CHAT_MESSAGE':
const index = state.tasks.findIndex(elm => elm.userid === action.taskid)
const task = state.tasks
return update(
state, { tasks: { index: { $set: action.task } } })
I would like to use index inside update function but my IDE alerting me that index is declared nut never used.
Since index is dynamic, you must use [] with it, otherwise it will just be setting the index key
case 'ADD_CHAT_MESSAGE':
const index = state.tasks.findIndex(elm => elm.userid === action.taskid)
const task = state.tasks
return update(
state, { tasks: { [index]: { $set: action.task } } })