Is there any way to return an entire namespace via the translate function in i18next? - i18next

in my case,i need get the entire namespace as an object,is there any can do this?
i have try this code,but just return undefined。
// the bookingPage is a namespace
t('bookingPage',{ returnObjects: true })

It is not possible with the t function, t function returns a string.
You can get an access to the entire i18n object which has methods for this.
// your-component.jsx
const YourComp = () => {
const { i18n } = useTranslation();
console.log(i18n.store.getResourceBundle('en', 'bookingPage')); //<-- will return the entire namespace
return <div>Bla</div>;
};

Related

calling an array method on a computed property

I have an array:
const arr = []
I then have a computed property:
const filtered_arr = computed(() => {
//...
}
I then have another computed property: filtered_arr2 where I want to call some() method on the first filtered_arr.
But getting errors since filtered_arr is not an actual array.
const filtered_arr2 = computed(() => {
filtered_arr.some((e)=>{}) // <- error
}
UPDATED:
Getting several errors :
some is not a function
Container is not set or can not be properly recognized. Use container() method to set it
I think my whole approach is buggy...
From the API documentation...
computed()#
Takes a getter function and returns a readonly reactive ref object
and
ref()#
Takes an inner value and returns a reactive and mutable ref object, which has a single property .value that points to the inner value
So with that in mind, you'll need to use the .value property within your setup
const filtered_arr = computed(() => {
// return some array
});
const filtered_arr2 = computed(() => {
const isPresent = filtered_arr.value.some(...);
// return some other value
});

Vue Reading in parallel in a loop

I have an Set array which contains multiple Ids.I would like to loop through the Set and make the api calls in parallel for each id and get back the user object, add it to a map.How can i achieve it.
The value is Set
userIds :Set[2]
0:"1"
1:"2"
data() {
return {
userIds: new Set(),
};
},
const res = getUsers(userId)
hope it will resolve your issues. i did not test, just writing code here directly.
// set requests
let allRequests = []
//you can use other loop based on your decession
this.userIds.forEach(id => { allRequests.push(axios.get(`your_url\${id}`)) })
// you can use await it is based on you requirement
axios.all(allRequests).then(axios.spread((...responses) => {
//make your map here using responses
})).catch(errors => {
// react on errors.
})
you can check this reference

i18n won't translate correctly when inside array or object in React Native

I'm trying to use i18n-js to translate some strings into other languages. If I have my code in normal code, it works. Ex:
//Displays "Something" (no quotes) where I want it
<Text> translate("Something"); </Text>
But if I put it inside an array or object, then call it later, it stops working and shows a missing message instead of the text I want translated. Ex:
const messages = {
something: translate("Something"),
// other translations...
}
// later on
// Displays "[missing "en.Something" translation]" (no quotes) where I want it
<Text> messages.something </Text>
The following is my code for my translate function, as well as the config for i18n. I'm using lodash-memoize, but that is unrelated to the issue. I've already checked that the text being passed to i18n.t() is the same (including type) no matter if it's in normal code or in the array, but it still doesn't return the correct thing. I have some error checking written up to avoid getting the missing message on screen, but that still doesn't fix the issue that it can't find the translation.
export const translationGetters = ({
en: () => require('./translations/en.json'),
es: () => require('./translations/es.json')
});
export const translate = memoize(
(key, config) => {
text = i18n.t(key, config)
return text
},
(key, config) => (config ? key + JSON.stringify(config) : key)
);
export const setI18nConfig = () => {
// fallback if no available language fits
const fallback = { languageTag: "en", isRTL: false };
const { languageTag, isRTL } =
RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
fallback;
// clear translation cache
translate.cache.clear();
// update layout direction
I18nManager.forceRTL(isRTL);
// set i18n-js config
i18n.translations = { [languageTag]: translationGetters[languageTag]() };
i18n.locale = languageTag;
};
I have no idea where to go on this. Any advice would be appreciated!
Same problem here, workaround is to return array/object from inside a function:
Don't work
export const translations = [i18.t('path')]
Works
export function getTranslations() {
const translations = [i18.t('path')]
return translations
}

Using async await on promise in svelte (#await) is not returning the desired data that is formatted in a later function call

I am currently working with a API that does not return JSON. To get around this, I take the response and push it to a array ( while formatting it to remove any indentation and split each number in the response ). I then use this array of 183 numbers and run a for loop against an array with 183 characters to generate an object ( with custom key value pairs ) from the response.
Where things get confusing is when I start to use the data in my HTML. Usually you can just say <p>{data.overallRank}</p> but I am getting the error that the object is undefined. This makes sense because the data = {} was not created until the function ran.
After searching for a solution, I cam across svelte await blocks. You can read on them here and look at the tutorial : https://svelte.dev/tutorial/await-blocks
After trying to implement this feature, I have the following code.
let playerStats = []
let proxy = "https://cors-anywhere.herokuapp.com/"
let url = proxy + "https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=Hess"
const data = {};
let promise = getPlayer();
async function getPlayer() {
return await fetch(url).then((response) => response.text())
.then((data) => {
return data;
});
}
getPlayer().then((playerData) => {
// format data
playerStats.push(playerData.replace(/\n/ig, ",").split(','));
console.log(playerStats);
// Begin object generation
// names array shortened
let names = ["overallRank", "overallLvl", "overallXP", "attRank", ]
const data = {};
for (var i = 0; i < playerStats[0].length; i++) {
data[names[i]] = playerStats[0][i];
}
console.log(data);
});
<main>
{#await promise}
<p>Search for a Player...</p>
{:then data}
<p>The data is {data}</p>
{/await}
</main>
I suggest throwing this code in a svelte editor which you can find here: https://svelte.dev/tutorial/await-blocks
The issue with this code is that it is printing out the data from the return data, which returns the unformatted data and not the object.
I want to return the object that is created after the second function getplayer().then()... so I can use that object throughout my HTML.
I hope I explained things well and thank you in advance for any help.
It is returning the formatted data because that what is returned by the promise function. In order to get the formatted data, you have to add the formatting to the chain of promise
async function getPlayer() {
return await fetch(url)
.then((response) => response.text())
.then((playerData) => {
// here your transformation
// do not forget to actually return something
return data;
});
You were actually very close to sorting it out, just a bit of confusion regarding how promises work I believe.
All you need to do is format your data within the block where the data is handled following the fetch & decode operations:
async function getPlayer() {
return await fetch(url)
.then((response) => response.text())
.then((data) => {
return formatData(data);
});
}
Your formatData() function is essentially there already, you just need minor changes in your code:
function formatData(playerData) {
playerStats.push(playerData.replace(/\n/ig, ",").split(','));
console.log(playerStats);
// Begin object generation
// names array shortened
let names = ["overallRank", "overallLvl", "overallXP", "attRank", ]
const data = {};
for (var i = 0; i < playerStats[0].length; i++) {
data[names[i]] = playerStats[0][i];
}
console.log(data);
return data;
}
Finally, you do not need to explicitly declare a promise to use it in an {#await} block, you know getPlayer() returns a promise, so you can directly use that instead:
<main>
{#await getPlayer()}
<p>Search for a Player...</p>
{:then data}
<p>Overall Rank: {data.overallRank}</p>
{/await}
</main>
See functioning REPL

Declaring getter property when building SpyObj using jasmine.createSpyObj utility?

Let's say I have a class:
class MyRealClass {
get propOne() { return stuffFromTheServer; }
}
When testing, I want to achieve this functionality:
const mockClass = {
get propOne() { return someStuff; }
}
jasmine.spyOnProperty(mockClass, 'propOne', 'get');
By doing something like this...
const spy = jasmine.createSpyObj('mockClass', [
{methodName: 'propOne', accessType: 'get'}
]);
In other words, I want to build a SpyObj<MyRealClass> using the jasmine.createSpyObj and declare the getter properties as methods in the methodName array (the second parameter the the createSpyObj() method.
Is this possible?
createSpyObj takes an optional last parameter that lets you declare properties:
const spy = jasmine.createSpyObj(['here', 'be', 'methods'], { propOne: 'someStuff' });
or
const spy = jasmine.createSpyObj('mockClass', ['here', 'be', 'methods'], { propOne: 'someStuff' });
See here and here for the official docs
I did it surprisingly simple by this code:
const routerMock = jasmine.createSpyObj(['events']);
routerMock.events = of(new NavigationEnd(0, 'url1', 'url2'));
const serviceToTest = new SomeService(routerMock);