How to fetch data in vueJS? - javascript

a column data is showing in array : ["1k","2k","3k"]
I used foreach to filter and the data type is showing string and it shows like this again: ["1k","2k","3k"]
If I convert this into an array then v-for loop does not show data.
photographers data is the API action state.
Output: I want to print each value in dropdown from this array.
I am trying to do v-for on print.
I tried to do print as a computed function but no result.
If you want all code then I can print its too much logic that's why I have trimmed it which is required.
Thanks
code:
data() {
return {
print: [],
printPrice: [],
},
computed: {
getImageDetails(){
this.photographersdata.forEach((details) => {
if(details.id === parseInt(this.imageId)){
this.print = details.print;
this.printPrice = details.print_price;
}
})
},```

Related

React/Mobx mapping observable array to components

I'm stuck with trying to map an array to display components for each entry. Here's what I'm doing currently,
Here's my RankStore;
const RankStore = observable({
loading: false,
error: "",
rank: {} as RankInfo,
LoadRank() {
this.loading = true;
this.error = "";
GetRankInfo()
.then(action((json:any) => {
this.rank = json.rankDetails;
console.log(json)
this.loading = false;
}))
.catch(action((error: any) => {
this.error = error.message;
this.loading = false;
}));
}
});
export default RankStore;
In this observable RankStore I am loading the rank, which fetches from an API, and setting it to 'rank' which is an array of my model RankInfo, shown below;
interface RankInfo {
serviceNumber: string
capBadge: string
endDate: string
equivalentNatoRank: string
mainTrade: string
regtCorps: string
seniorityDate: string
actingPaidRank: string
startDate: string
substantiveRank: string
}
export default RankInfo;
Information received from the API looks like so;
Ordinary, to display this in a component, I would make the component an observer and simply call {RankStore.rank.serviceNumber} which works for my other Stores but not for this one as the data is a array containing two items. I am trying to MAP each array to a component so for each array it shows a component such as <h1> {RankStore.rank.serviceNumber} </h1> in this case it would render two components showing the respective service Numbers.
In the past I have done this as so;
{this.state.tickets.map((ticket) => (
<text key={ticket.id} value={ticket.id}>
{ticket.ticketApplication.firstName}{" "}
{ticket.ticketApplication.lastName}
</text>
))}
However, anytime I try to map {RankStore.rank} I always get 'MAP does not exist in 'rank''. What is the appropriate way to map arrays to components with MOBX?
It seems that you are setting the rank field as an object initially, and after the API call, changing it to an array. When rank is an object, it doesn't have the map function property on it.
So, instead of:
rank: {} as RankInfo
do this:
rank: [] as RankInfo[]
Initialize as an empty array of the RankInfo type.

Show length of data array in VueJS after getting the data from API

I'm using Vue JS to get some data from an API. I want to get the length of this array and log to console via a method.
But it always logs the value of "0" instead of the real length.
I can access the data in the html without any problem and show the length ( {{ termine.length }} ).
But I want to do it using the method "logToConsole".
It seems to be a problem to access the data (which seems to be undefined in the moment of function call).
I fetch the data on "created", and output the length in "mounted", so it should be available (?).
Do you have any idea why I cannot access the data of the array in my "mounted" function, even after getting the data in "created"?
new Vue ({
el: "#calendar",
data: {
termine: [],
},
},
created() {
fetch("https://www.myurl.com/data/?json&function=GetEvents")
.then(response => response.json())
.then((data) => {
this.termine = data;
})
},
mounted() {
this.logToConsole();
},
methods: {
logToConsole: function () {
console.log(this.termine.length);
},
},
})
Of course, created hook is triggered before mounted.
But you know, you are setting termine property using API response and it is happen with async.
If you simple set termine property with simple statement like this.termine = ['a', 'b'], it will logs 2.
If you want log the data after getting the value using API, you could use watch.
like:
watch: {
termine(val) {
console.log(val)
}
}

How to create an object through loop using vue multiselect

I'm using vue multiselect for a project with laravel.
The selected values are saved in the database in this way.
['value_on','value_two','value_three', and so on...]
In the part where the user can do the updates I need to display the values coming from the database.
This is the object I need to create
sizeValue: [
{size: 'val_one},
{size: 'val_two},
{size: 'val_three}
...and so on
]
Right now I just have an empty array where I should loop the data from the database.
//This is the empty array
sizeValue: [];
//This is the array coming from the server it will return['val_one','val_two','val_three',...and so on]
product.sizes
Since I don't have much experience with javascript I would like to ask how I can get this result
sizeValue: [
{size: 'val_one},
{size: 'val_two},
{size: 'val_three}
...and so on
]
looping the values (product.sizes) coming from the DB in the empty sizeValue.
you could simply create the sizeValue as a computed property and use the javascript map function.
This could look like this:
<script>
export default {
computed: {
sizeValue() {
return this.product.sizes.map(productSize => {
return {
size: productSize
};
});
}
}
};
</script>
Hope this helps :)

How to use toString() to convert an Array to String format for dynamically selected values

In my React application, I have a filter component. Everytime I apply filters, I am calling an api by passing the selected filter values from Front End. Filter component has checkboxes so when I am selecting multiple values, it is being passed as an array of strings currently. I want to send the selected filter values as string instead of Array of Strings. I have total 2 filters- Date, Name. In my Parent component, the filters param in handleFilterChange will have all two values i.e Name as Array of Strings and Date as String which I am sending in request payload as part of filterCondition object. I want to change Name alone to String.
ParentComponent.js-
const ParentComponent = props => {
const [filterObj, setFilterObj] = useState({});
const handleFilterChange = filters => {
console.log(filters); // Show the filter values-Date(String), Name(Array of Strings)
const reqParams ={
id,
filterCondition: filters // An object with Name(Array) and date(string)
}
setFilterObj(filterObj);
//API call which will pass filters in request params
fetchApi(reqParams);
};
return (
<ChildComponent onChange={handleFilterChange} />
);
}
fetchApi will always send name and Date in filterCondition object. My code is working fine, the only change I want to do now is to change Array to String for name.Currently, with the above code my request structure looks like this-
Current Request Structure-
{
id:1,
filterCondition: {
name: ['XYZ', 'ABC'],
date: '2020-06-29T00:00:00'
}
}
I want my request to be like below-
Expected request structure-
{
id:1,
filterCondition: {
name: 'XYZ, ABC',
date: '2020-06-29T00:00:00'
}
}
Can someone help me understand how can I achieve the above expected request structure.
To convert Array to String you can use join(separator) function
var obj = {
id:1,
filterCondition: {
name: ['XYZ', 'ABC'].join(','),
date: '2020-06-29T00:00:00'
}
}
console.log(obj);

Vuejs : v-model with multiple checkbox in v-for

I have some questions about using v-model with "complex" object. Here's my code:
<v-list v-for="(facet, facetName) in getFacets" :key="facetName">
<v-list-tile-content v-for='valueFacet in facet" :key="valueFacet.key">
<v-checkbox v-model="selectedFacets[facetName]" :value="valueFacet.key"></v-checkbox>
</v-list-tile-content>
</v-list>
And here's my data / init:
data() {
return {
selectedFacets: {}
}
},
created: function() {
// I initialize my object with all my facets here
config.facets.forEarch(facet => {
this.selectedFacets[facet] = [];
});
}
Some explanation: each facet has multiple checkbox representing values. We can select multiple values. My object has to be like this :
selectedFacets: { facet1 : [value1, value2], facet2: [value12, value 13]
With this code, each time I select one value, it will remove the previous one.
I tried to initalize my object in my data like this without using created function:
data() {
return {
selectedFacets: { "facetName" : [], "facetName2" : []}
}
}
and it works fine. All my values for each facet are added in the right array. But I need to initialize my object and facet names with my conf and if I don't initialize my object in my data, it does not work. I tried with computed / created, by getting my object from my store, but it keeps adding value by removing the previous one.
Any idea about what I do wrong ? Thanks.
Just initialize your object with Vue.set:
created: function() {
config.facets.forEach(facet => {
Vue.set(this.selectedFacets, facet, []);
});
}
When component initializes template it doesn't know about selectedFacets[facetName] so to make it reactive and correct working with v-model you should use Vue.set mutator.

Categories

Resources