Im using React, Apollo and Graphcool. I have an account page where I need to query the logged in users details:
const loggedInUser = gql`
query {
loggedInUser {
id
}
}
`;
Logging in is done on a separate page. If the user then navigates or is automatically redirected (both with React Router) to the account page then the query comes back as null. If I give the page a hard refresh then the logged in users ID comes back from the query successfully.
Im not sure why this is happening. I don't think it could be a race condition as you can navigate to the account page after 10 seconds and it still wont return the user id unless you refresh.
Do I need to user resetStore? This could be expensive for me as a lot of data which wont have changed will need to be fetched again.
I needed to refetch the query after the user logged in as Apollo had cached the previous result of null. I added this to the login function and it now works.
// I added this:
await this.props.loggedInUser.refetch();
// redirect user
this.setState({
redirect: true,
});
Related
So basically I have a chat app in html and nodejs and js and I am trying to load messages that were sent previously so people can see chat history if they join but when they join it works but if say I reload the page on my computer while they are on the site it would send duplicate value when I want it to only show once.
let msgArray = []
const updateCounter2 = ctx => {
ctx.io.emit('count', Object.keys(ctx.io.sockets.sockets).length);
for (var i in msgArray) {
ctx.io.emit('message', msgArray[i]);
}
};
server([get('/', ctx => render('msg.hbs')),
socket('connect', updateCounter2),
socket('message', ctx => {
console.log(ctx.data);
ctx.io.emit('message', ctx.data);
msgArray.push(ctx.data)
})
]);
is part of my code but this is the code to get messages and push them to an array to display when a user loads the page.
Like if I reload the page it works fine but if I reload once someone is on it they get sent the data once again which is not supposed to happen.
Like I am probably repeating myself but I open the page on my phone and on my computer and when I have it open on computer and phone and reload on phone it sends duplicates to computer. (but then if I reload it removes the duplicates and only sends the non dupes)
Sending clientside message worked
ctx.socket.emit('message', msgArray[i]);
We are using React + React-Redux + Redux-Saga in our application, and the withRouter part of react-router-dom is used when connecting to the redux store.
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
Issue Steps:
I have all users listed on the users landing page.
I click on one of the users, then the redirect happens using the withRouter, history.push function, which kicks the redirect on this.props.history.push(${REDIRECT_URL});, this shows the current clicked user-profile data.
Now I come back to the users landing page
I click on another user, it again kicks in the this.props.history.push(${REDIRECT_URL});, and the previously visited users data is shown in a blink of an eye or some milliseconds, and then the newly clicked user-profile data is shown.
reduxForm connected for my application is below
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(reduxForm({
form: 'userProfile', // this form needs to be fixed I guess with passing other `(k,v)` to the `reduxForm`
enableReinitialize: true,
})(UserInformation)));
Is there a way to fix this? to not show the previously visited users data? Appreciate help or pointers.
I have a page where it has 2 different endpoint calls to 2 different routes around the same time. The second one returns successfully, however, the first one stays in pending status.
I have checked the server logs and the request is received by the server and a response is sent back.
For some reason, the status code of the pending one is 200 even though it says pending.
I tried to replicate this problem in multiple machines but failed. However, in the users' machine, it can be replicated every single time.
The user does not have any browser extensions. (Tried on incognito and problem still occurs)
All calls are in https
The page which does the requests generally has ~100% CPU for a few seconds.
After waiting for a while the user gets the Page unresponsive tab.
Users Chrome version: 81.0.4044.26 / macOS Mojave. I also tested with the same versions and couldn't replicate.
I'm using axios and the following code to fetch data.
const fetchData = async () => {
try {
const result = await axios(url);
..
} catch (error) {
..
}
};
I couldn't figure out why this was happening and how to fix it. Would appriciate help.
Thanks
Related Topic: What does "pending" mean for request in Chrome Developer Window?
I have developed one dashboard application in angular js which is having search functionality and multiple views with lots of different data coming from that search functionality.
Its single page application. So I am facing issue on page reload all data is gone and it shows view with blank data.
Is there any way to solve this issue or any language which help me to create single page application and maintain same data on page reload??
Any suggestion will be appreciated.
Search Page
Data after search
Data after reload
You can use sessionStorage to set & get the data.
Step 1 :
Create a factory service that will save and return the saved session data based on the key.
app.factory('storageService', ['$rootScope', function($rootScope) {
return {
get: function(key) {
return sessionStorage.getItem(key);
},
save: function(key, data) {
sessionStorage.setItem(key, data);
}
};
}]);
Step 2 :
Inject the storageService dependency in the controller to set and get the data from the session storage.
app.controller('myCtrl',['storageService',function(storageService) {
// Save session data to storageService on successfull response from $http service.
storageService.save('key', 'value');
// Get saved session data from storageService on page reload
var sessionData = storageService.get('key');
});
You need to save data before changing the state of application / moving to another page,route.
So, either save that data using
Angular services (Save data, change route, come back check the data in service and reassign variables from service.)
Local-storage to save data. (Save data, change route, come back check the data in service and reassign variables from service.)
Rootscope. Set data in rootscope and move .. after coming back check the variables and reassign.
Your problem is not saving the data, but saving the state in your URL. As it is, you only save the "step", but no other information, so when you reload the page (refresh, or close/re-open browser, or open bookmark, or share...) you don't have all the information needed to restore the full page.
Add the relevant bits to the URL (as you have a single page app, probably in the fragment identifier). Use that information to load the data, rather than relying on other mechanisms to pass data between the "pages".
Get data on page refresh, that is something like,
$rootScope.on('onStateChangeStart', function(){
// here make a call to the source
$http(); // request and try to get data
})
use localStorage or save data to your server for users in a database temporarily and get it back with an API call(localstorage has a 10MB) limit.
You can have your code try to retrieve localstorage values first if they exist.
Say a user is browsing a website, and then performs some action which changes the database (let's say they add a comment). When the request to actually add the comment comes in, however, we find we need to force them to login before they can continue.
Assume the login page asks for a username and password, and redirects the user back to the URL they were going to when the login was required. That redirect works find for a URL with only GET parameters, but if the request originally contained some HTTP POST data, that is now lost.
Can anyone recommend a way to handle this scenario when HTTP POST data is involved?
Obviously, if necessary, the login page could dynamically generate a form with all the POST parameters to pass them along (though that seems messy), but even then, I don't know of any way for the login page to redirect the user on to their intended page while keeping the POST data in the request.
Edit : One extra constraint I should have made clear - Imagine we don't know if a login will be required until the user submits their comment. For example, their cookie might have expired between when they loaded the form and actually submitted the comment.
This is one good place where Ajax techniques might be helpful. When the user clicks the submit button, show the login dialog on client side and validate with the server before you actually submit the page.
Another way I can think of is showing or hiding the login controls in a DIV tag dynamically in the main page itself.
You might want to investigate why Django removed this feature before implementing it yourself. It doesn't seem like a Django specific problem, but rather yet another cross site forgery attack.
2 choices:
Write out the messy form from the login page, and JavaScript form.submit() it to the page.
Have the login page itself POST to the requesting page (with the previous values), and have that page's controller perform the login verification. Roll this into whatever logic you already have for detecting the not logged in user (frameworks vary on how they do this). In pseudo-MVC:
CommentController {
void AddComment() {
if (!Request.User.IsAuthenticated && !AuthenticateUser()) {
return;
}
// add comment to database
}
bool AuthenticateUser() {
if (Request.Form["username"] == "") {
// show login page
foreach (Key key in Request.Form) {
// copy form values
ViewData.Form.Add("hidden", key, Request.Form[key]);
}
ViewData.Form.Action = Request.Url;
ShowLoginView();
return false;
} else {
// validate login
return TryLogin(Request.Form["username"], Request.Form["password"]);
}
}
}
Just store all the necessary data from the POST in the session until after the login process is completed. Or have some sort of temp table in the db to store in and then retrieve it. Obviously this is pseudo-code but:
if ( !loggedIn ) {
StorePostInSession();
ShowLoginForm();
}
if ( postIsStored ) {
RetrievePostFromSession();
}
Or something along those lines.
Collect the data on the page they submitted it, and store it in your backend (database?) while they go off through the login sequence, hide a transaction id or similar on the page with the login form. When they're done, return them to the page they asked for by looking it up using the transaction id on the backend, and dump all the data they posted into the form for previewing again, or just run whatever code that page would run.
Note that many systems, eg blogs, get around this by having login fields in the same form as the one for posting comments, if the user needs to be logged in to comment and isn't yet.
I know it says language-agnostic, but why not take advantage of the conventions provided by the server-side language you are using? If it were Java, the data could persist by setting a Request attribute. You would use a controller to process the form, detect the login, and then forward through. If the attributes are set, then just prepopulate the form with that data?
Edit: You could also use a Session as pointed out, but I'm pretty sure if you use a forward in Java back to the login page, that the Request attribute will persist.