someone please tell me how to fix this issue , this function is calling multiple times , i don't know why and it is so annoying to fix
function NewProduct({ navigation }) {
const supplierApi = useApi(suppliers.getSuppliers);
useEffect(() => {
supplierApi.request();
}, []);
return console.log(supplierApi);
}
the log is like below...
{data: Array(0), error: false, loading: false, request: ƒ}
{data: Array(0), error: false, loading: true, request: ƒ}
{data: Array(0), error: false, loading: false, request: ƒ}
{data: Array(0), error: false, loading: false, request: ƒ}
{data: Array(7), error: false, loading: false, request: ƒ}
You can call the function as follows, this will same as componentDidMount for class component.
function NewProduct({ navigation }) {
useEffect(() => {
const supplierApi = useApi(suppliers.getSuppliers);
supplierApi.request();
console.log(supplierApi);
}, []);
}
Related
i18next not working when passing multiple modules like i18next-http-backend and react-i18next and #os-team/i18next-react-native-language-detector
here is the sample code
i18n
.use(RNLanguageDetector)
.use(initReactI18next)
.use(Backend)
.init(
{
compatibilityJSON: 'v3',
fallbackLng: 'en',
supportedLngs: ['en', 'ar'],
load: 'languageOnly',
// ns: ['translations'],
// defaultNS: 'translations',
ns: ['common'],
defaultNS: 'common',
debug: true,
interpolation: {
escapeValue: false,
formatSeparator: ',',
},
react: {
useSuspense: true,
},
backend: {
crossDomain: false,
withCredentials: false,
overrideMimeType: false,
// loadPath: '${SERVER_APTH}/{{lng}}.json',
request: function (options, url, payload, callback) {
console.log('Request here to get from API');
},
reloadInterval: false,
allowMultiLoading: true,
},
initImmediate: false,
},
(error, t) => {
console.log('loading complete');
console.log('Error', error);
},
);
i18n.languages = ['en', 'ar'];
i18n.on('languageChanged', nextLng => {
console.log('Changed', nextLng);
});
Also tried with custom language detector
const languageDetector = {
type: 'languageDetector',
async: true,
detect: cb => {
console.log('Tagging here');
cb('en');
},
init: () => {},
cacheUserLanguage: () => {},
};
custom language detector work when i comment backend: { ... } section.
I need to store changed language and get translations according to it.
for changing i'm using
i18n.changeLanguage(nextLocale);
Where nextLocale will be "en" or "ar"
I got a weird error randomly while running my code and here is the code. Please comment if more details are needed.
action.js
export function generateIDs() {
return ({
type: GENERATE_IDS
})
}
reducer.js
const initialState = fromJS({
fields: {
task_completion_date: { ...initialDateState },
sale_id: { ...initialFieldState },
client_id: { ...initialFieldState }
},
progressvalue: 1,
submitting: false,
submitted: false,
valid: false,
statusText: '',
saleID: null,
clientID: null,
reportID: null,
reportDate: datestring,
isLoading: false,
online: true
});
I create a simple Vue.js plugin, and want to test that with npm and jest.
One function should return a document element by id, but it return always null.
Why is that and how can i fix it?
// plugintest.js
const PluginTest = {
install(Vue, options) {
Vue.mixin({
methods: {
getBool: function() { return true; },
getElem: function(id) { return document.getElementById(id); }
}
});
}
}
export default PluginTest;
//plugintest.spec.js
let Vue = require('vue/dist/vue')
import PluginTest from './plugintest.js';
Vue.use(PluginTest);
describe("plugintest.js", () => {
test('test functions', () => {
const wrapper = new Vue({
template: '<div id="div1">Hello, World!</div>' }).$mount();
expect(wrapper.getBool()).toBe(true);
expect(wrapper.getElem('div1')).not.toBe(null); // FAIL!!!
});
});
Error message:
expect(received).not.toBe(expected) // Object.is equality
Expected: not null
19 |
20 | expect(wrapper.getBool()).toBe(true);
> 21 | expect(wrapper.getElem('div1')).not.toBe(null);
| ^
22 | });
23 | });
24 |
at Object.toBe (plugintest.spec.js:21:39)
console.log(wrapper.$el) output:
HTMLDivElement {
__vue__:
Vue {
_uid: 1,
_isVue: true,
'$options':
{ components: {},
directives: {},
filters: {},
_base: [Object],
methods: [Object],
template: '<div id="div1">Hello, World!</div>',
render: [Function: anonymous],
staticRenderFns: [] },
_renderProxy:
Vue {
_uid: 1,
_isVue: true,
'$options': [Object],
_renderProxy: [Circular],
_self: [Circular],
'$parent': undefined,
'$root': [Circular],
'$children': [],
'$refs': {},
_watcher: [Object],
_inactive: null,
_directInactive: false,
_isMounted: true,
_isDestroyed: false,
_isBeingDestroyed: false,
_events: {},
_hasHookEvent: false,
_vnode: [Object],
_staticTrees: null,
'$vnode': undefined,
'$slots': {},
'$scopedSlots': {},
_c: [Function],
'$createElement': [Function],
'$attrs': [Getter/Setter],
'$listeners': [Getter/Setter],
_watchers: [Object],
getBool: [Function: bound getBool],
getElem: [Function: bound getElem],
_data: {},
'$el': [Circular] },
_self: [Circular],
'$parent': undefined,
'$root': [Circular],
'$children': [],
'$refs': {},
_watcher:
Watcher {
vm: [Circular],
deep: false,
user: false,
lazy: false,
sync: false,
before: [Function: before],
cb: [Function: noop],
id: 2,
active: true,
dirty: false,
deps: [],
newDeps: [],
depIds: Set {},
newDepIds: Set {},
expression: 'function () {\n vm._update(vm._render(), hydrating);\n }',
getter: [Function: updateComponent],
value: undefined },
_inactive: null,
_directInactive: false,
_isMounted: true,
_isDestroyed: false,
_isBeingDestroyed: false,
_events: {},
_hasHookEvent: false,
_vnode:
VNode {
tag: 'div',
data: [Object],
children: [Object],
text: undefined,
elm: [Circular],
ns: undefined,
context: [Circular],
fnContext: undefined,
fnOptions: undefined,
fnScopeId: undefined,
key: undefined,
componentOptions: undefined,
componentInstance: undefined,
parent: undefined,
raw: false,
isStatic: false,
isRootInsert: true,
isComment: false,
isCloned: false,
isOnce: false,
asyncFactory: undefined,
asyncMeta: undefined,
isAsyncPlaceholder: false },
_staticTrees: null,
'$vnode': undefined,
'$slots': {},
'$scopedSlots': {},
_c: [Function],
'$createElement': [Function],
'$attrs': [Getter/Setter],
'$listeners': [Getter/Setter],
_watchers: [ [Object] ],
getBool: [Function: bound getBool],
getElem: [Function: bound getElem],
_data: {},
'$el': [Circular] } }
Try using vm.$el.
expect(wrapper.$el).not.toBe(null);
The root DOM element that the Vue instance is managing.
Reference
NOTICE
If you want to access another elements, your code could look something like this:
expect(wrapper.$el.querySelector("div")).not.toBe(null);
Another option is to use VueTestUtils's find mthod: https://vue-test-utils.vuejs.org/api/wrapper/find.html#find
Using VueTestUtils
Try using attachToDocument option.
Reference
import { mount, createLocalVue } from "#vue/test-utils";
import PluginTest from "./plugintest.js";
const localVue = createLocalVue();
localVue.use(PluginTest);
it("plugintest.js", () => {
const component = {
template: "<div id="div1">Hello, World!</div>"
}
const wrapper = mount(component, {
localVue,
attachToDocument: true
});
expect(wrapper.vm.getElem("div1")).not.toBe(null);
});
I think you'r missing the parameter for getElem(), try it like:
expect(wrapper.getElem('div1')).not.toBe(null);
i want to integrate this toast only if axios post is executed. i placed it like that and it's shown up even if my post axios function is not working.
how can i fix that ?
My code:
methods: {
addRinvoice: function () {
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
axios.post('/addrinvoice', this.rinvoice)
.then(response => {
toast({
type: 'success',
title: 'Invoice added in Database'
}),
console.log(response.data);
if (response.data.etat) {
this.rinvoice = {
id: 0,
amount: response.data.etat.amount,
};}})
.catch(error => {
console.log('errors: ', error)
}) },
Just put your call invoking the toast method inside your then() method:
methods: {
addRinvoice: function () {
axios.post('/addrinvoice', this.rinvoice)
.then(response => {
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
toast({
type: 'success',
title: 'Invoice added in Database'
}),
console.log(response.data);
if (response.data.etat) {
this.rinvoice = {
id: 0,
amount: response.data.etat.amount,
};}})
.catch(error => {
console.log('errors: ', error)
})
},
place it inside then after getting response successfully like :
then(response=>{
...
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 9000
});
toast({
type: 'success',
title: 'Invoice added in Database'
}
}
I'm trying to add a element to a array, which is called allLogbooks. This array contains objects called Logbook. My issue is, how do I fit in code so that it adds the new element to the array which is declared in my reducer? This is my initial state:
const initialState = {
isFetching: false,
error: undefined,
isRegistered: false,
isUpdated: false,
hasChecked: false,
isError: false,
registerStepOne: true,
registerStepTwo: false,
registerStepThree: false,
registerStepFour: false,
logbooks: undefined,
allLogbooks: [],
userInfo: undefined,
logbookAddSuccess: false,
newLogbook: undefined,
graphFilter: 1
}
This is my reducer:
case ADD_LOGBOOK_SUCCESS:
allLogbooks.push(action.newLogbook);
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
}
And this is my action:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS
}
}
I then make a POST call to a nodejs server, where it will respond with a message if it was successful, and the logbook which was just created. the following data is what it returns:
{
"success": true,
"logbook": {
"created_by": "",
"created_at": "",
"_id": "",
"__v": 0
}
}
I then dispatch in the API call, as such:
.then(data => data.json())
.then(json => {
Keyboard.dismiss();
dispatch(addLogbookSuccess(json.logbook));
})
.catch(err => dispatch(addLogbookFailed(err)))
I've substituted this by using AsyncStorage to access the array abroad all my views, but I know this is wrong.
I am struggling a little to comprehend your question so I've tried my best. Please let me know if I'm completely off with my answer.
Your reducer:
case ADD_LOGBOOK_SUCCESS: {
const newLogbook = action.payload;
return {
...state,
isFetching: false,
logbookAddSuccess: true,
isUpdated: true,
isError: false,
allLogBooks: [
...state.allLogBooks,
newLogbook
]
}
}
Your action:
function addLogbookSuccess(newLogbook) {
return {
type: ADD_LOGBOOK_SUCCESS,
payload: newLogbook
}
}