Can't get cookies with js-cookie and react - javascript

I'm using Nextjs and trying to make multi language application. Multi langugage working properly but when I'm trying get language code with cookie like 'en', getting error.
This way working;
initialLang = 'en';
setDefaultTranslations({en, fr});
setLanguage('en');
But when I'm trying to set initialLang with cookie not working.
This way not working
initialLang = Cookies.get('lang');
setDefaultTranslations({en, fr});
setLanguage(initialLang);

To solve your problem you need to step back and understand the problem. The main problem about the cookie is you need to split your code to read&write cookie for server and client. js-cookie works for only client-side. Basically, it works on the client because it works with document.cookie. When it calls document in next.js SSR, the backend code is not able to read the document because it does not exist. If you would like to read cookie in SSR you need to catch it from expressjs request and pass into react state. I would recommend you to use https://github.com/andreizanik/cookies-next which already solves this problem (implementation)

Probably, you're not using them in componentDidMount hook:
componentDidMount() {
// get cookie
// set state to update the language
}

Related

How to get localStorage value on client-side from global middleware using Nuxt.js

I have implemented functionality for change theme between dark and light in my Nuxt.js project, but I have one more problem.
After user changes in setting theme he gets flag in local storage. Flag _t (theme) and values - _d is for dark and _l is lor light. Depending on these values script has to set attribute data-theme to dark or light and then, depending on scss variables theme will be set.
The problem is - how can I get this value from localStorage. Of course, on every page I can create mounted() hook and check for value in localStorage, but I have to do this on every page I create and it doesn't seem to be normal solution. I was thinking about global middleware and created one.
export default function() {
if (process.server) return
const t = localStorage.getItem('_t')
if (!t) {
localStorage.setItem('_t', '_d')
document.documentElement.setAttribute('data-theme', 'dark')
} else {
document.documentElement.setAttribute('data-theme', t === '_l' ? 'light' : 'dark')
}
}
I works, but not quite right. Nuxt.js works with SSR, so basically the first time middleware is called on server, and only then on client side. That's why I have this if (process.server) check, because localStorage is unavailable on server side.
The problem of this solution is, after page reload you won't see in HTLM this data-theme="dark". And because of this, styles seem to be 'broken'. It works only if you go to this page by clicking on nuxt-link, because it works on client side.
So, what would be the best practice in this case. Is any opportunity to implement this check globally and not to check for localStorage value in mounted() hook on every page?
You can use the same approach but instead of using localStorage you can use cookies, as cookies are sent via every HTTP request, so you can access it on the server-side and client side.
You can use this library for managing your cookies.
https://www.npmjs.com/package/cookie-universal-nuxt
For more resources about cookies.
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

nextjs api not working when fetching through isomorphic-unfetch

Im not getting my data (notes) inside the props, it is giving undefined when im using console.log(notes).
My backend api is also in the same project in /pages/api/notes/index.js
The api which im calling is 'http://localhost:3000/api/notes'
Even my api is working fine when im testing it on postman. But on the frontend, data isnt available
Please checkout this issue.
I believe that you simply have a typo. Index.getinitialProps should be Index.getInitialProps. Note that the "i" in initial is capitalized.
Also as a tip, you don't explicitly need http://localhost:3000, if you just call it with /api/notes it will correctly resolve the request. That way when you deploy the app you don't have to go back and make a ton of changes for your data fetches.

error when I try to fetch calendar events through google API, JS React

For some reason; I get error when trying to get my calendar events through google API. I code in JS and use React and have no idea why it does not work.
I have the token stored in sessionStorage and do get personal information about the user like name email and such stuff but I cannot proceed and get the calendar events. Please help!
I'm not sure what exactly you would like to see inside my App but let me know and I'll provide with the stuff because I do not want to upload the whole project lol
https://gyazo.com/37433e19f07e441adf368d1bbcad78e6
Maybe try to return res.send as you use async/await and it returns promise
I changed the structure of the app and I do now receive cal events when I hit one of my endpoints, but receiving other kind of error now, anyway this one can be closed.
Cross-origin request blocked, origin 'null' no access

Store information on client using AngularJS

I am working on an app, similar to DHC by Restlet . I would like to be able to store headers (which are inputed by user, just like in Dev HTTP Client) in a cookie or something similar to have the possibility to "remember" which headers were inputed by the user like in Dev HTTP Client. I am trying to make this with $cookie and $cookieStore, but it doesn't seems to work well (on Chrome cookies aren't saved at all, and on FireFox they disappear if the browser is relaunched).
This is how it looks like (checkbox is used to save/remove header from cookies and plus - add new header):
Please, point me to the solution or provide some useful links / articles, provide your own thoughts! Every answer is highly appreciated and answered immidiately.
Thank you.
I'd say that using a module using HTML5 local storage would be a good idea; for example, using angularLocalStorage, you would inject it in your module (don't forget to include the cookie fallback)
angular.module("surveillance", ['ngCookies','angularLocalStorage']);
then bind a property to the local storage:
storage.bind($scope, "queries", {
defaultValue:[{
"title" : "angularjs is used in this app",
"search" : "https://api.stackexchange.com/2.2/search/advanced?page=1&pagesize=25&order=desc&sort=creation&closed=False&tagged=angularjs&site=stackoverflow"
}
]
});
Now any change to the queries property of your scope will be persisted between calls.
In order to see a demo, you can have a look at this page that i wrote that lets you keep favorite searches on stackoverflow (full source code: disclaimer i was just working on this when i saw your post while testing the app :) )

How to post Facebook Score using JS SDK, without hardcoding the app access token?

I'm trying to post a score using the JS SDK. Here's the code that I'm using:
FB.api("/[USER_ID]/scores", 'post', {score:score, access_token:"APP_ACCESS_TOKEN"}, function(response){
if (!response || response.error) {
log(response);
} else {
log(response);
}
});
However, I need to do this without hardcoding the APP_ACCESS_TOKEN. Any idea on how to do it using the JS SDK?
/me/ refers to the current user - when using the app access token there is no 'current' user - you're acting as the app - make the request to /[USER ID]/scores using the app access token
You can grab access_token through JS by using FB.getLoginStatus. More can be found in the doc.
.
There is no way, that I know of.
And, nor should there be, when you consider that the App will only have one app access_token.
Think of it like your app secret, keep it safe!
Especially when you consider how you get the access_token to start with, just by making a formatted request to FB with your ID and App Secret.
If you put that client side, then ANYONE could grab it and do stuff on behalf of your app!!
I would suggest one of two things:
Try making a call to /me/scores, and use the normal access token.
Even though the API docs don't suggest this being possible, you never know.
OR
2. Encapsulate it as an AJAX call to your server, and make the Graph call from there.
Sucks, but there seems to be a few things that aren't quite designed to work on the client side yet. :-/

Categories

Resources