I have a component where I can click to "add a study". This click triggers two things :
1 - post in my API
2 - adding to my state to re-render the component.
So, it works BUT when I record the data in my state, I have not the ID of the study and I need it after. So is it possible to do something to have this ID ? Or I am forced to re-call my API to get all my studies ?
My code in my component :
const addStudy = {
name : this.newStudy.nameStudy,
status: "In prepa",
project: "api/projects/" + this.newStudy.currentIdProject,
compareStudy: false,
basic: true
}
axios
.post('http://127.0.0.1:8000/api/studies', addStudy)
.then(this.$store.commit("addStudie", {projet : this.newStudy.currentIdProject, study :addStudy}))
And in my store :
addStudie(state, {projet, study}) {
const theProject = state.listProjects.projects.find(p => p.id === projet)
theProject.studies.push(study)
}
Thanks a lot
i seems there is an issue with the request. In my opinion, it should change to
axios
.post('http://127.0.0.1:8000/api/studies', addStudy)
.then((result)=>{
this.$store.commit("addStudie", {projet : this.newStudy.currentIdProject, study :result
})
})
if you have any problem place let me know
You can save your ID in the localStorage that saves key value string data on the client side (browser)
addStudie(state , id) {
// do somthing with state then save it into localStorage
localStorage.setItem('myID', id);
}
And a store getter that returns the id from localStorage
theId(state) {
const savedID = localStorage.getItem("myID")
return savedID
}
if(theId()){
// do something with your ID
}
else{
// ID is not saved in the localStorage yet , call the API
getDataFromAPI()
}
Related
I am trying to get some data from an API. The problem is that the GET call could take none or some of the filters. I have tried but am not sure how/if I can create a URL with conditional filters.
actions: {
InstitutionSearch(value, id){
let fips = id['ParamValues'].find(o=>o.param==='fips')['value'];
let region = id['ParamValues'].find(o=>o.param==='region')['value'];
axios.get('https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/',{
params:{
fips: ,
region: region,
offering_highest_level: 3
}
})
};
}
This is a vue application, with the code above running inside a vuex store. The id that is being passed in is an array of objects, that is taken from a search filter form. The problem that I have is that my query could include either fips or region or none.
My initial thought was the put fips and region equal to 0, but that does not work with my API. I am not opposed to building a query string inside conditionals, but there has to be an easier way. The following is an actual query for the data that I am working with https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/?offering_highest_level=3.
With some amazing help, I figured out a simple solution. I created an empty object and then ran a conditional check on my parameters and only added them, if they met my qualifications. I then passed that object in as the parameters, and everything worked.
let fips = id['ParamValues'].find(o=>o.param==='fips')['value'];
let region = id['ParamValues'].find(o=>o.param==='region')['value'];
//code change
let params = {};
fips.length > 0 ? params['fips'] = fips.join(',') : null;
region != 0 ? params['region'] = region : null;
//code change
axios.get('https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/',{
params
}).then(response=>{
console.log(response.data.results);
});
useEffect(() => {
axios
.get(
`http://stream-restaurant-menu-svc.herokuapp.com/item?category=${props.data}`
)
.then((response) => {
console.log("This is to show sub-categoary " + response.data);
setSubcate(response.data);
})
.catch((error) => {
console.log(error);
});
},[props]);
i want to to update child value depending on categoryId. I tried following this tutorial Firebase DB - How to update particular value of child in Firebase Database. It’s work, but it’s not storing in the same ref. It’s store in another ref.
https://i.stack.imgur.com/SaqjD.png
firebase.database().ref('usuario')
.on('value',event =>{
event.forEach(user =>{
user.child('eventos').forEach(evento =>{
if (evento.val().categoryId === payload.id){
//Here is where i try to update the childe value, in my case category
let ref = firebase.database().ref('usuario/'+user.key+'/'+evento.key+'/'+evento.val().category)
.set(payload.name)
console.log(ref)
}
})
});
});
2 problems:
1.You forgot to add "\eventos" on you child path.
2.dont use .set(), because it will delete all the other data.
Instead of .set() use .update().
Try this code:
firebase.database().ref('usuario')
.on('value',event =>{
event.forEach(user =>{
user.child('eventos').forEach(evento =>{
if (evento.val().categoryId === payload.id){
//Here is where i try to update the childe value, in my case category
let ref = firebase.database().ref('usuario/'+user.key+'/eventos/'+evento.key+'/'+evento.val().category)
.update(payload.name)
console.log(ref)
}
})
});
});
Let me know if it still dont work
I'm trying to build a simple app that lets the user type a name of a movie in a search bar, and get a list of all the movies related to that name (from an external public API).
I have a problem with the actual state updating.
If a user will type "Star", the list will show just movies with "Sta". So if the user would like to see the actual list of "Star" movies, he'd need to type "Star " (with an extra char to update the previous state).
In other words, the search query is one char behind the State.
How should it be written in React Native?
state = {
query: "",
data: []
};
searchUpdate = e => {
let query = this.state.query;
this.setState({ query: e }, () => {
if (query.length > 2) {
this.searchQuery(query.toLowerCase());
}
});
};
searchQuery = async query => {
try {
const get = await fetch(`${API.URL}/?s=${query}&${API.KEY}`);
const get2 = await get.json();
const data = get2.Search; // .Search is to get the actual array from the json
this.setState({ data });
} catch (err) {
console.log(err);
}
};
You don't have to rely on state for the query, just get the value from the event in the change handler
searchUpdate = e => {
if(e.target.value.length > 2) {
this.searchQuery(e.target.value)
}
};
You could keep state updated as well if you need to in order to maintain the value of the input correctly, but you don't need it for the search.
However, to answer what you're problem is, you are getting the value of state.query from the previous state. The first line of your searchUpdate function is getting the value of your query from the current state, which doesn't yet contain the updated value that triggered the searchUpdate function.
I don't prefer to send api call every change of letters. You should send API just when user stop typing and this can achieved by debounce function from lodash
debounce-lodash
this is the best practise and best for user and server instead of sending 10 requests in long phases
the next thing You get the value from previous state you should do API call after changing state as
const changeStateQuery = query => {
this.setState({query}, () => {
//call api call after already changing state
})
}
I am building an application in which I want to save user data. and user able to see that data later. I am using AsyncStorage.. i want to store multiple values in one key. I used AsyncStorage.setItem.. here is my code..
var obj ={
name : "sabih",
color : "blue"
}
AsyncStorage.setItem('myKey', JSON.stringify(obj))
.then(() => {
console.log('data saved')
})
but when i get data with AsyncStorage.getItem. it gives me like this
{"name":"sabih" , "color" : "blue"}
Code here
AsyncStorage.getItem("myKey").then((data) => {
var userData = JSON.parse(data)
console.log(userData, 'Get Values')
}).done();
How can i set name's and color's value in state. or how can i render these values in my react native application..
Thanks in advance.
and please attach a snap of solution if possible..
Create a function inside your file and call that function passing your asyncstrorage value as parameter as below :-
_renderDetail=(item)=>{
this.setState({user:item});
}
and inside your asyncStorage code edit as :-
AsyncStorage.getItem("myKey").then((data) => {
var userData = JSON.parse(data);
console.log(userData, 'Get Values');
this._renderDetail(userData);
}).done();
and then you can use this state variables inside your render function as :-
<Text>{this.state.user.name}</Text>
<Text>{this.state.user.color}</Text>
I need your help or suggestion regarding my refresh function. I have this button called refresh that when clicked it will refresh (rearrange the data sorting based on createdAt field). I have been battling for days trying to get this correctly by resubscribing which i am not sure if it is the correct way or not.
Is there a correct way to resubscribe or re-sorting an a collection on the client when button clicked? Thanks a lot.
Yes, you can do this with following steps:
Pass the sorting type(asc or desc) into router query.
Update the subscribe sorting of server.
You need to also also update your client side find() methods sort, because when data does not change or few document get updated by your re-subscription, SO the oldest data will always come at first.
You can subscribe or re-subscribe collection on either router level or template level. If you are using Flow Rotuer then your re-subscribe will not work simply because flow router is not reactive. I prefer to use subscription at template level. Using Iron router query.
Here is the code sample :
Templete.templeteName.onRendered(function(){
this.autorun(function(){
var sort = {};
if(!Router.current().params.query || Router.current().params.query.sortType == 1 ) {
sort.createdAt = 1;
} else {
sort.createdAt = -1;
}
//You can use this handle to show/hide loader.
var handle = Meteor.Subscribe('subscriptionName', sort);
})
})
Templete.templeteName.helpers({
'data' : function(){
var sort = {};
if(!Router.current().params.query || Router.current().params.query == 1 ) {
sort.createdAt = 1;
} else {
sort.createdAt = -1;
}
return collection.find({},{sort:sort});
}
});
Templete.templeteName.events({
'click .refresh' : function(){
var sortType = value //get the value -1 or 1 from html.
Router.go('routeNaem',{},{query:{sortType:sortType}})
}
});