IE 11, Data from server not update - reactjs

I have strange problem with IE11 only. I have form in my app, when I fill all inputs and try save, request to server from IE11 is send properly, then I try get this data and I recive empty collection from resposne (using axios). I use polyfill to promises and push. Where could be a problem ?
In application I use React, Redux.
Sample code:
getService(id) {
return this.api.get('/' + id)
.then(resp => {
console.log(resp.data.model.collect) // arr length 0 in other browser data are exist here
let Collection = [];
resp.data.model.collect.map((item, idx) => {
Collection.push(item)
});
return Collection;
})
.catch(err => {
throw err;
})
}

the problem is that the internet explorer browser uses data cache for load form. It's necessary stop to record cache. for this you need request your api puting in header the pragma parameter
header {
pragma: 'no-cache'
}

Related

Chrome and Edge hang on React page load for only some users, should I change my useEffect strategy?

My ReactJS project displays a simple page consisting of a header section with project title, version and a few nav links, then a table of about 200 results as the main content of the page.
The initial page loads for everyone and the components appear as expected, but on page load (I believe this is when the useEffect hook kicks in) some users report the page becoming un-responsive and no matter how long it is left, it never finishes. This has been reported in both Chrome and Edge by 5 different users across a site of 200+ users, the majority have no issues despite running the exact same hardware and connection.
On page load, I expect the title, version and table contents (plus a few other variables) to be populated and automatically updated since these are in state, and for most users, this works as expected.
Below is my useEffect()
useEffect(() => {
// Update all initial values
fetchLastUpdated();
fetchVersion();
fetchUsername();
fetchUpcomingFilterOptions();
fetchLongCustomerNames();
fetchConfigs();
fetchUpcomingResults() // This will be displayed as rows
const job = document.getElementById("job")
if ( !!job ) {
job.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
submitForm()
}
});
}
// Find environment for API links: testing/pre-release, testing/QA, flx
const url = window.location.href
if ( url.includes('localhost') ) {
setEnvironment("testing/pre-release")
} else if ( url.includes('testing/pre-release') ) {
setEnvironment("testing/pre-release")
} else if ( url.includes('testing/QA') ) {
setEnvironment("testing/QA")
} else if ( url.includes('flx') ) {
setEnvironment("flx")
}
}, [])
Below an example of an API call from useEffect
const fetchConfigs = () => {
axios({
method: "get",
url: "http://myURL/" + environment + "/WITracker/public/api/myConfigs",
config: { headers: {
'Access-Control-Allow-Origin': '*',
"Content-Type": "multipart/form-data"
}}
})
.then(function (response) {
setConfigs(response.data);
})
.catch(function (response) {
console.log("Failed to fetch configs!");
addNotification("Unable to fetch configs", "Retry in progress...")
})
}
When remote accessing the users with troubles loading the page, I asked that they each try the alternative browser: Chrome -> Edge or Edge -> Chrome and in each case this resolved the issue. I found this strange as I would have expected the same browser to be causing the same behaviour each time across the users.
I would like to make sure that the page reliably loads for all users regardless of their browser preference. I'm at a bit of a loss trying to find out why only some users are getting unresponsive errors so any possible solutions or suggestions of what to try are welcome!
Possible workaround?
I'm not sure that I have set up my useEffect the correct way using best practices. I'm thinking of adding a slight delay to the API calls, since the page loads the components without issue, and once the delay is up, to synchronously make each of the calls, giving the browser more of a chance to process the smaller chunks of work rather than all at once... please can somebody let me know their thoughts on this?
e.g. Something similar to the below theory?
useEffect(async () => {
// Some delay here, with loading screen
wait(1000) //custom function to wait?
// ...then, update all initial values
await fetchLastUpdated();
await fetchVersion();
await fetchUsername();
await fetchUpcomingFilterOptions();
await fetchLongCustomerNames();
await fetchConfigs();
await fetchUpcomingResults()
...
Thanks in advance

Update React Component With Updated Data From Firestore

I have a chrome extension that stores data in Firestore and populates that data to the frontend. I always have to refresh the page to see newly added data, which isn’t a user friendly experience. How can I update the UI to show the newly updated data without having to refresh the page?
So far, I've tried using useEffect to get the data. Inside of it, I'm using a function that gets data from Firestore cached inside of chrome local storage.
Here is my code
const getFolderData = () => {
getDataFromChrome("docId").then((res: any) => {
setDocId(res.docId);
});
getDataFromChrome("content").then((res: any) => {
//console.log("getting in mainfolder",res);
// for (const item of res.content) {
// if (item.type.toLowerCase() === "subfolder") {
// // console.log(item)
// getSubFolder(item.id);
// }
// }
for (const item of res.content) {
setTiersContent((pre: any) => [...pre, item]);
}
});
};
useEffect(() => {
getFolderData();
}, []);
I also get this error. I'm also using the chrome extension API to communicate with a background script. It could be related to the problem
Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
I've never used firebase so I'm not sure what your functions do, I can only guess. A few things wrong from what I can see:
Your useEffect is set to only run on page load since the dep array is empty, I assume you want to refetch on some condition.
If any of the 2 functions is supposed to be a subscription, your useEffect needs to return a cancel function.
Refetch data when needed is not a new problem, packages like React Query has tools that optimize your requests and refetch when needed. I suggest you give it a shot if your app has more than 2-3 fetch requests.

Invalid character found in method name error when fetching an api using React

I have implemented a table using ag-grid react. I fetch data from an api to fill in that table.
const getDataForTable = async () => {
try {
//apis to fetch the data
setGridData(apiData);
}
catch (err) {
console.error(err);
}
}
useEffect(() => {
getDataForTable();
}, []);
Now, I have also created an onClick method for deleting selected rows of the table. I am removing the rows from api as well. Once the rows are deleted, I just want to refresh the grid with updated data. Currently it only works if I explicitly reload the page.
const onClickRemoveRowsByIds = async () => {
selectedRows.forEach(d => {
listOfIds.push(d.Id);
});
if (window.confirm("Are you sure ?")) {
await listOfIds.map((ele) => removeActiveList(ele));
getDataForTable()
}
}
But when I make a call to getDataForTable function, I get bad request error for the apis. On looking at the reponse body of the api : I get Invalid character found in method name. HTTP method names must be tokens. The authToken and rest of the information remains same but still fetch is not working again. Am I missing some step, or doing it completely wrong? The delete works fine, just the refresh is not happening.

Fetch status 200 but pending endllessly, except first call

I've been searching to solve this problem for a while but couldn't find a working solution.
I'm making a simple social network website and this API returns a article data such as text, image and video url, etc, all saved in server's local MySQL Database. My front-end is React and server is Nginx reverse proxy with Node.js using Express. When I load the page, I create 5 React components that each make fetch request for given article number.
The following code snippet is the fetch API that asks the server to fetch data from database:
//server-side script
app.get('/api/getArticle/:id', (req, res) => {
const con = mysql.createConnection({
host: 'myhost_name',
user: 'myUser',
password: 'myPassword',
database: 'myDB',
});
con.connect(function (err) {
if (err) {
throw err;
}
console.log("Connected!");
})
const idInterest = req.params.id.toString();
console.log(idInterest)
let sql = 'some_sql';
con.query(sql, function (err, result) {
if (err) {
res.status(500).send("Error while getting article data");
return;
}
else {
res.set('Connection', 'close')
res.status(200).send(result);
console.log("ended")
con.end();
return;
}
})
}
//React script
//index.js
fetch('http://mywebsite.com/api/getMaxArticleId/')//Retrieve top 5 article ID
.then((response) => {
for (let i = 0; i < data.length; i++) {
nodesList.push(<Container articleId={data[i]['id']}/>)
}
ReactDOM.render(<React.StrictMode><NavBar />{nodesList}<Writer writer="tempWriter" /></React.StrictMode>, document.getElementById('root'));
})
//Container.jsx; componentDidMount
const url = "http://mywebsite.com/api/getArticle/" + this.props.articleId.toString();
fetch(url, {
method: 'GET',
credentials: "include",
}).then((response) => {
response.json().then((json) => {
console.log(json);
//processing json data
This used to work very fine, but suddenly the getArticle/:id calls started to show 200 status but 'pending' in 'time' column in Chrome network tab, endlessly, all except the first*getArticle/:idcall. This prevents my subsequent .then() in each Container from being called and thus my entire tab is frozen.
Link to image of network tab
As you see from the image, all pending fetches are missing 'Content Download' and stuck in 'Waiting(TTFB)', except the first call, which was '39'
I checked the API is working fine, both on Postman and Chrome, the server sends result from DB query as expected, and first call's Json response is intact. I also see that console.log(response.json()) in React front-end shows Promise{<pending>} with *[[PromiseStatus]]: "Resolved"* and *[[PromiseValue]]* of Array(1) which has expected json data inside.
See Image
This became problematic after I added YouTube upload functionality with Google Cloud Platform API into my server-side script, so that looks little suspicious, but I have no certain clue. I'm also guessing maybe this could be problem of my React code, probably index.js, but I have no idea which specific part got me so wrong.
I've been working on this for a few days, and maybe I need common intelligence to solve this (or I made a silly mistake XD). So, any advices are welcomed :)

AngularJS - POST request reload

I am searching solution for this question more than 3 day and can't find anything..
I have ionic3 App and working width Http POST requests. I am sending requests to my php server and geting data..
My data-api.ts (provider)
public getNotifications(token){
return this.http.post(this.sharedVars.getApi(),"action=messages/notification&token="+token, this.options
).map(res => res.json());
}
profilePage.ts
notifications() {
this.api.getNotifications(this.user.token).subscribe(
data => {
if(data.err == 0){
this.notifications = data.data;
}
},
err => {
console.log(err);
}
);
}
This is working functions and I am getting right output (1) when click this function. but on x action on my server notification count will changed to 2, 3, 4 etc.. and I want load this function not on click, but on page load. so If this.notifications have new value I want change value live (like as firebase)
Example 2:
I have send message action in my data-api.ts (provider)
public sendMessage(token, to, message, attachment){
return this.http.post(this.sharedVars.getApi(),"action=messages/send&token="+token+"&to="+to+"&message="+message+"&attachment="+attachment, this.options
).map(res => res.json());
}
and also have function to get this messages.
public getActivity(token){
return this.http.post(this.sharedVars.getApi(),"action=messages/getActivity&token="+token, this.options
).map(res => res.json());
}
so if I am making post request to sendMessage then I want listen live getActivity action and load new message in my page but not reload.. like as firebase..
I hope this question is clear. because I am not english speaker and tryng to find solution. Tanks
Listening actively to live events is not possible with a single HTTP request in angular.
However you might look into eventSources.
Look at this question for using with angular 2+ :
Creating an RxJS Observable from a (server sent) EventSource

Resources