i have a simple input form where i put a list of strings , then for each element of the string (string[i]) i run an ajax Get request to my api .
so here is the ajax request :
async function getUsers(props){
try{
const response = await Axios.get(`url=`+props)
console.log(response)
return response;
}catch{
console.log("response failed")
}
}
and i run it here :
... some code here ...
for(var i =0; i < string.length; i++){ // map the entery (string)
getUsers(string[i]).then(res => {
this.setState({
string2:res // this one is just for testing
});
console.log(res.data.id);
mystring22.push({res});
console.log("me inside the promise : " + this.state.string2.data.id);
})
setTimeout(() => {
console.log("iam not empty " + this.state.string2.data.id);
console.log(mystring22);
/* -----------------
I WANT TO DO SOME WORK HERE
-----------------*/
}, 3000);
this.setState({
string3 : mystring22
})
... some code here ...
so everything works fine , and my problem is the following :
the code take too much time (3 second for each request ) , is there is a way to change the code so it can do "SOMETHING" after each request , i tried to delete the setTimeout or reduce it but that not working the array is undefined after that .
hope you can help me .
thank you
setState is an async function, so when you call:
setState({ string2: res });
this.state.string2; // OUTDATED
in order to access the updated value, you must use the callback:
setState({ string2: res },
() => { console.log(this.state.string2) }); // UP TO DATE
as you can see in this codesandbox example, with the callback on line 27 and without the callback on 33.
Related
I am trying to set up a simple endpoint in SvelteKit that reads the input given in a form and returns the result of an SQL query. In my first attempt I used the form actions and wrote the following code in the +page.server.js file:
export const actions = {
default: async (event) => {
let form_input = await event.request.formData();
let query = {
text: "select * from ux_return_shipments($1, $2, $3, $4)",
values: [form_input.get('beg-dep-date') || null, form_input.get('end-dep-date') || null, form_input.get('beg-arr-date') || null, form_input.get('end-arr-date') || null
}
try {
const result = await event.locals.pool.query(query);
return result.rows;
} catch (e) {
console.log(e);
}
}
};
I am now trying to set up the same process using a GET request instead of a POST one but I am having difficulties setting up the endpoint. I tried to replace the above code with this template but it looks like the endpoint is not getting activated since I see no activity server side:
export function GET({ url }) {
console.log(url);
return new Response("Test response");
};
What am I doing wrong? I see that using this code for an API endpoint (+server.js file) works correctly. I also checked the form element and the URL looks correct.
In case someone has the same problem I managed to solve it using this template:
export const load = async (event) => {
return ...
};
Using the load function I was able to set up a get endpoint and pass some data to the frontend using a return.
I am working on google extensions. I am trying to process message passing between my popup.tsx and background.ts
Before sending message from my background.ts, I print the data. Data exist. However, in my popup.tsx chrome.runtime.onMessage not triggered. I dont understand which function not working and what is the problem. I examine lots of example but result still the same. What is the problem? I am adding my message passing codes..
Here is my background.ts runtime.sendMessage func. this function is inside another function that is called 'collectData'. When I open new tab or update the tab, this function triggered and works. Everytime this data works stable. I can see the data in every page.
chrome.runtime.sendMessage({
msg: 'url_data',
data: data,
})
Then, I am trying to receive the data in my popup.tsx with runtime.onMessage. When I reset the extension, it works sometimes just once, then that onMessage func not working at all :
const [requestData, setRequestData] = useState<string>()
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log(' popup runtime on message req', request)
if (request.msg === 'url_data') {
checkWebsite(request.data).then((res) => {
console.log('popup data alındı')
console.log('popu res', res)
setRequestData(res)
// chrome.runtime.sendMessage({
// msg: 'res_length',
// data: res.matches.length,
// })
// console.log('popup data res length gönderildi')
// res.matches.length === 0 ? setIsSecure(true) : setIsSecure(false)
setHost(request.data.hostname)
})
sendResponse({ message: 'res length sended' })
console.log('res length response send')
}
})
Everytime, I change request data state. If it changes, I want to update popup with useEffect.
useEffect(() => {
console.log('useeffect', requestData)
}, [requestData])
As a result, for the first the main problem is message passing. Why it is not working?
I'm fairly new to React and stuck regarding a very minor problem. I wrote an UI that essentially calls a service that returns the responses in the form of an array. Now, I need those responses from the service to be displayed in the form of a nested menu. For e. g., one of my axios calls returns a response of [1,2,3,4] and the other axios call returns [1.1,1.2,1.3,..]. I want these responses to be aligned in the form of
1
1.1
1.2
1.3
2
2.1
etc.,
i. e. the UI should show 1,2,3,4 .. and when the user clicks on 1, then 1.1,1.2 etc. should be displayed.
I'm using React, material-ui's components and redux for this.
I have a function to do the above mentioned.. but I'm not sure if I'm doing it right.
handleMenuData() {
var applist = this.props.menuData;
var appNames = [];
var moduleNames = [];
applist.forEach(app => {
app.moduleNames.forEach(module => {
try {
return axios.get(
'service url' + app.name + '/' + module,
);
} catch (error) {
console.error(error);
}
});
appNames.push({
name: app.name,
moduleNames: moduleNames,
});
moduleNames = [];
});
this.setState({
appNames: appNames,
});
}
and in my state,
this.state = {
appList: [],
appNames: [],
moduleNames: [],
};
app names are 1,2,3 and module names are 1.1,1.2 and I was thinking of using ListItemText component from material UI.
I think what you are doing is incorrect. axios.get is an asynchronous function and you are not waiting for the response to come from the server. That's why you get all arrays as empty. Try calling a recursive function like this.
const getModuleNames = (i) => {
axios.get('service url' + applist[i].name + '/' + module)
.then((response) => {
if(i < applist.length){
applist[i].moduleNames = response.data;
appNames.push({
name: applist[i].name,
moduleNames: applist[i].moduleNames
});
getModuleNames(i++);
}
else {
// code you want to execute after adding data to appNames
}
}).catch((err) => {
// error handling
});
}
getModuleNames(0);
I'm having problems using findOne because it always returns undefined.
This code:
Routine.js
Meteor.methods({
.... // Some lines missing
'routines.getRoutine'(routineId) {
check(routineId, String);
return Routines.findOne(routineId);
},
});
Note: If I do a console.log of Routines.findOne(routineId) it correctly shows the element that i'm looking for.
App.jsx
handleSubmit(event) {
event.preventDefault();
const comment = ReactDOM.findDOMNode(this.refs.comment).value.trim();
Meteor.call('routines.addComment', this.state.routine._id, comment);
let a = Meteor.call('routines.getRoutine', this.state.routine._id);
ReactDOM.findDOMNode(this.refs.comment).value = '';
this.setState({
routine: a,
});
}
In my Appjs doesn't matter how I try 'a' is always undefined, what am I doing wrong?
Thanks for the help in advance!
I'm pretty sure your problem is that Meteor calls on the client are async and so the method you're calling hasn't completed by the time you're querying the same data.
Try putting the rest of the code in the callback like so:
handleSubmit(event) {
event.preventDefault();
const comment = ReactDOM.findDOMNode(this.refs.comment).value.trim();
Meteor.call('routines.addComment', this.state.routine._id, comment, function() {
let a = Meteor.call('routines.getRoutine', this.state.routine._id);
ReactDOM.findDOMNode(this.refs.comment).value = '';
this.setState({
routine: a,
});
});
}
I'm writing an app in react native, and I'd like to query and API I have. The API is really simple and just spits out some text on a web page.
I've been using this:
var value = '';
fetch("http:myapi.com/")
.then((response) => response)
.then((responseData) => {
value = responseData._bodyText;
console.log(responseData._bodyText); //prints what I want
})
.done();
console.log(value); //prints an empty string
I'd like to set the value of the var "value" to the response's text. Doing a console.log has shown that responseData._bodyText does have the information I want, but when I try setting the var value to responseData._bodyText, value isn't set and the variable remains empty.
How should I remedy this?
response is a response object, and not a promise. You probably want response.json() or response.text()
var value = '';
fetch("http:myapi.com/")
.then((response) => { return response.text() }) // change to return response.text()
.then((text) => {
value = text;
})
.done();
Probably an asynchronous problem. If you were logging out responseData._bodyText inside the callback at the end of the fetch promise chain then it would probably be correct but if you were logging the assigned value variable and seeing the empty string I would assume you are logging at a point before the fetch promise has been resolved.
var value = '';
fetch("http:myapi.com/")
.then((response) => response.text())
.then((text) => value = text)
.done();