I'm learning Redux and Redux Toolkit, but I don't understand why autocomplete doesn't work when I'm trying to dispatch an action (see the image below).
I imported the "action" but WebStorm can't see any methods.
On VSCode it works very well.
Here the action :
import {createSlice} from "#reduxjs/toolkit";
const initialCounterState = { counter: 0, showCounter: true };
const counterSlice = createSlice({
name: "counter",
initialState: initialCounterState,
reducers: {
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
},
increase(state, action) {
state.counter += action.payload;
},
toggleCounter(state) {
state.showCounter = !state.showCounter;
},
},
});
export const counterActions = counterSlice.actions;
export default counterSlice.reducer
Like you can see above , the first image is WebStorm , the second is vscode.
Vscode detects all the methods , WebStorm doesn't , I didn't find any issue like these on google..
I'm wondering if it's simply normal to not see theses methods on WebStorm , it would be weird , WebStorm it's powerful usually..
I just found the solution, experimenting with different ways or rearranging my files. I'm taking the same tutorial with the same profesor at Udemy. Is just a matter or organizing your files and imports/exports in a specific way.
Instead of exporting each SliceAction directly from its respective slice file, each one of them must be centralized on the store index file and exported from there.
Solution: Code example:
File: src/store/counterSlice.js
import {createSlice} from '#reduxjs/toolkit';
const counterInitialState = {
counter: 0,
showCounter: true,
};
const counterSlice = createSlice({
name: 'counterSlice',
initialState: counterInitialState,
reducers: {
incrementCounter(state) {
state.counter++;
},
decrementCounter(state) {
state.counter--;
},
increaseByCounter(state, action) {
state.counter = state.counter + action.payload.amount;
},
decreaseByCounter(state, action) {
state.counter = state.counter - action.payload.amount;
},
toggleCounter(state) {
state.showCounter = !state.showCounter;
},
}
});
export default counterSlice;
File: src/store/authSlice.js
import {createSlice} from '#reduxjs/toolkit';
const authInitialState = {
isAuthenticated: false,
};
const authSlice = createSlice({
name: 'authSlice',
initialState: authInitialState,
reducers: {
logIn(state) {
state.isAuthenticated = true;
},
logOut(state) {
state.isAuthenticated = false;
},
toggleLogging(state) {
state.isAuthenticated = !state.isAuthenticated;
},
}
});
export default authSlice;
File: src/store/index.js
import {configureStore} from '#reduxjs/toolkit';
import counterSlice from "./counterSlice";
import authSlice from "./authSlice";
const store = configureStore({
reducer: {
counterSliceReducer: counterSlice.reducer,
authSliceReducer: authSlice.reducer,
},
});
export const counterSliceActions = counterSlice.actions;
export const authSliceActions = authSlice.actions;
export default store;
After organizing your files this way, you will see that now you have a perfect visibility over the action creator methods in your imported CaseReducerActions object (like authSliceActions or counterSliceActions, for example).
So this is how my WebStorm IDE looks like right now:
File: src/App.js
File: src/components/Counter/Counter.jsx
As you can see, now I have auto completion (autocomplete feature) using WebStorm.
Even if you are not using TypeScript directly and only write JavaScript, your editor will still use a library's TypeScript typings to give you things like autocomplete. So even if you are not directly using TypeScript yourself, this is still relevant to you.
This is a known issue, but it is a bit broader:
Unfortunately, WebStorm does not work very well with TypeScript and where other editors just use the library's TypeScript typings (even in JavaScript scenarios) for autocomplete and error messages, WebStorm just randomly guesses wrong stuff because things have kinda similar names.
For Redux Toolkit specifically, there are multiple issues open in their bug tracker and they do a great job at ignoring that: https://youtrack.jetbrains.com/issue/WEB-46527 and https://youtrack.jetbrains.com/issue/WEB-42559 for example.
So yes, due to bugs in WebStorm it is unfortunately "normal to not see theses methods on WebStorm" until the bugs I linked above are fixed.
At this point I can only recommend not using WebStorm for any kind of software development involving JavaScript or TypeScript.
Visual Studio Code might need a few extensions hand-picked and installed to get on feature parity with WebStorm, but it is free and works very well, so I cannot recommend that enough.
Related
I'm trying to extract a function for use across multiple components, but "this" is undefined and I'm unsure of the best practice approach of how to attach the scope so my function knows what "this" is. Can I just pass it as an argument?
Component:-
import goToEvent from "#/common";
export default {
name: "update",
methods: {
goToEvent
common function:-
let goToEvent = (event, upcoming=false) => {
this.$store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
export default goToEvent
When I call goToEvent in my component, I get TypeError: Cannot read property '$store' of undefined. How do I avoid this?
In this situation I recommend to define eventable as a mixin :
const eventable= {
methods: {
goToEvent(event, upcoming=false) {
this.$store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
}
}
export default eventable;
in your vue file :
import eventable from "#/eventable";
export default {
name: "update",
mixins:[eventable],
....
second solution :
export an object with the function as nested method then import it and spread it inside the methods option :
export default {
goToEvent(event, upcoming=false){
this.$store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
}
then :
import goToEvent from "#/common";
export default {
name: "update",
methods: {
...goToEvent,
otherMethod(){},
}
//....
}
You're tagged with Typescript, so you need to tell TS that this actually has a value (note, I do not know VueJS, am using the generic Event types here, there is likely a more valid and correct type!)
First option, manually tell it what there is -
let goToEvent = (this:Event, event, upcoming=false) => {
Other option - tell it what type it is -
let goToEvent: EventHandler = (event, upcoming=false) => {
Of the two I personally prefer the second style for readability.
There are numerous ways to achieve this, here are some that I like to use in my projects:
Method 1: Mixins
Mixins are great for sharing a bunch of methods across components and also easy to implement, although one big con is that you will not be able to import specific methods that you need. Within the mixin, this follows the rules as in components.
File: #/mixins/eventable
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([])
goToEvent (event, upcoming = false) {
store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
}
}
Usage in component:
import eventable from '#/mixins/eventable'
export default {
name: 'ComponentName',
mixins: [eventable],
methods: {
componentMethod () {
this.goToEvent()
}
}
...
Method 2: Static JavaScript files
In some cases, you might have a collection of helper functions kept in a file and want the ability to import as you need.
In your case, you seem to be using a store actions (assumed from the dispatch), hence I'll be including importing and using the store within the static JS file.
File: #/static/js/eventable.js
import store from 'path_to_store_file'
const goToEvent = () => {
store.dispatch('actionName', payload)
}
export default {
goToEvent
}
Note:
Although this is not entirely necessary, but only by declaring the imported function as a method within the component will it be bound to the component instance. This will allow you to access the function in the HTML portion.
Usage in component:
import { goToEvent } from '#/static/js/eventable.js'
export default {
name: 'ComponentName',
methods: {
// Read note before this code block
goToEvent,
componentMethod () {
// When declared as a method
this.goToEvent()
// When not declared, it can still be accessed in the js portion like this
goToEvent()
}
}
...
I'm trying to use react-image-annotate but it's giving me this issue when I first try to set it up.
And here's how I'm using it:
import React from 'react'
import ReactImageAnnotate from 'react-image-annotate'
function ImageAnnotator() {
return (
<ReactImageAnnotate
selectedImage="https://images.unsplash.com/photo-1561518776-e76a5e48f731?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
// taskDescription="# Draw region around each face\n\nInclude chin and hair."
// images={[
// { src: 'https://example.com/image1.png', name: 'Image 1' },
// ]}
// regionClsList={['Man Face', 'Woman Face']}
/>
)
}
export default ImageAnnotator
I'm using Next.js if that matters
UPDATE 1
I tried using this babel plugin as suggested by Alejandro Vales. It gives the same error as before. Here's the babel key in my package.json:
"babel": {
"presets": [
"next/babel"
],
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-transform-modules-commonjs",
{
"allowTopLevelThis": true
}
]
]
}
I would say that the issue relies in the library itself by what they replied in here (similar bug) https://github.com/UniversalDataTool/react-image-annotate/issues/90#issuecomment-683221311
Indeed one way to fix it I would say is adding babel to the project so you can transform the imports in your project to require automatically without having to change the code on your whole project.
This is the babel package you are looking for https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs
Another reason for this could be an outdated version of your package, as some people report to have this fixed after using a newer version of Create React App (https://github.com/UniversalDataTool/react-image-annotate/issues/37#issuecomment-607372287)
Another fix you could do (a little crazier depending on your resources) is forking the library, creating a CJS version of the lib, and then pushing that to the library, so you and anybody else can use that in the future.
I got a tricky solution!
Problem is that react-image-annotate can only be imported in client-side(SSR got error for import keyword)
So, let react-image-annotate in Nextjs be imported only in client side
(https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr)
in Next Page that needs this component, You can make component like this
import dynamic from "next/dynamic";
const DynamicComponentWithNoSSR = dynamic(() => import("src/components/Upload/Annotation"), { ssr: false });
import { NextPage } from "next";
const Page: NextPage = () => {
return (
<>
<DynamicComponentWithNoSSR />
</>
);
};
export default Page;
Make component like this
//#ts-ignore
import ReactImageAnnotate from "react-image-annotate";
import React from "react";
const Annotation = () => {
return (
<ReactImageAnnotate
labelImages
regionClsList={["Alpha", "Beta", "Charlie", "Delta"]}
regionTagList={["tag1", "tag2", "tag3"]}
images={[
{
src: "https://placekitten.com/408/287",
name: "Image 1",
regions: [],
},
]}
/>
);
};
export default Annotation;
I've been working for the past two days on a task which is adding the capability to translate a whole website from English to Spanish when the user selects the toggle button, However, I'm really new into Redux (use it once on a completely different project). The people who gave me the code already configured the reducers, I just need to read the status on each component.
I've tried using this code on one of the components:
const store = createStore(reducer);
store.dispatch({
type: 'TOGGLE-LANG'
});
store.subscribe(() => console.log(store.getState()));
However, it is still has something missing, and at this point, I'm completely lost and I would love to have some guidance to know what to do.
I created a Gist with all the code involved in this task, It has commented on what's the expected behavior
[Gist Link] : https://gist.github.com/ManudeQuevedo/12cd63cf7431b5ec9b982a37391b7c56
Currently, there are no errors, it is recognizing the reducer (Lang), but I would love to know how to make it actionable in the other components that need to be translated. Thanks in advance!
You can use i18n. Replacing the text contents on your website to keys, and adding a map matching the keys to different languages.
For example, before you have
<div>
name:
</div>
Now it will be like:
<div>
{t('name')}
</div>
Here is the link of an example project
At the end this is what I did:
lang.js (reducer)
import { fromJS } from 'immutable';
const initState = fromJS({
value: 'en',
translations: {
en: {
component: {
title: 'Mobile Connectivity',
subtitle: 'Smart Messaging'
}
},
es: {
component: {
title: 'Conectividad Móvil',
subtitle: 'Mensajería Inteligente'
}
},
}
});
export default (state = initState, action) => {
switch (action.type) {
case "CHANGE_LANGUAGE":
return {
...state,
value: action.payload
};
default:
return state;
}
};
and I implemented it by destructuring it on this component like so:
[Gist][1]
I added it to a gist because it's a long code so it would be more readable like that.
I'm working on a Vue project on a static environment with no Node or Vue-cli,
We're importing Vue, Vuetify and vue-i18n using CDNs
We need to have the Vuetify components translated using the Vue-i18n like shown here
Here is a codepen of an attempt i've made, trying to translate the pagination part at the bottom.
I've tried using Vue.use() but couldn't get it to work, no errors in the console and no translation on the page.
import App from '../components/App.vue.js';
import i18n from '../lang/languages.js';
import store from './store/store.js';
Vue.filter('toUpperCase', function(value) {
return value.toUpperCase();
});
Vue.config.devtools = true;
Vue.use(Vuetify, {
lang: {
t: (key, ...params) => i18n.t(key, params)
}
});
new Vue({
i18n,
store,
el: '#app',
render: (h) => h(App)
});
lang/languages.js:
import { russian } from './languages/russian.js';
import { chineseSimple } from './languages/chinese-simple.js';
import { german } from './languages/german.js';
import { portuguese} from './languages/portuguese.js';
const languages = {
'ru': russian,
'zh-Hans': chineseSimple,
'de': german,
'pt': portuguese,
};
const i18n = new VueI18n({
locale: 'en',
messages: languages
});
export default i18n;
What you are looking for is not available in CDN distributions. You might ask why?
Look at this code:
const Vuetify: VuetifyPlugin = {
install (Vue: VueConstructor, args?: VuetifyUseOptions): void {
Vue.use(VuetifyComponent, {
components,
directives,
...args
})
},
version: __VUETIFY_VERSION__
}
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(Vuetify)
}
Especially this part:
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(Vuetify)
}
It automatically installs the Vuetify without any configurations such as language and etc, so your Vue.use(Vuetify, {..}) won't get called because Vue won't install plugins twice!
What you could do?
Clone the Vuetify repo and change this part of the code and build a new dist for your self.
Save as the file vuetify.dist.js and change that part of the code
Use some hacky tricky workarounds which I don't recommend, but I created a sample for you.
Here is a code pen example, What I actually do:
Load Vue.js file with scripts tag
Use fetch api to download content of vuetify.dist.min.js
Replace window.Vue to something else to make sure vuetify won't install itself automatically!
Eval the changed code
I DON'T RECOMMEND THIS APPROACH AT ALL
fetch("https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.5.14/vuetify.min.js")
.then(res => res.text())
.then(vutify => {
eval(vutify.replace("window.Vue", "window.Vue2"));
Vue.use(Vuetify, {
lang: {
t: (key, ...params) => i18n.t(key, params)
}
});
const App = Vue.component("app", {
template: `
I am refactoring some code in my app and turns out,the below logic it is repeated in many many components.
import component1 from '...'
import component2 from '...'
import component3 from '...'
//...many others
export default {
//other data
components: {
component1,
component2,
component3
//...
}
}
Does exists a shorter approach in order to clean my code?
Thanks for your time
Below are 3 ways.I prefer method 3 by the way.
Method 1
Create a js file in my case dynamic_imports.js:
export default function (config) {
let registered_components = {}
for (let component of config.components) {
registered_components[component.name] = () => System.import(`../${config.path}/${component.file_name}.vue`)
}
return registered_components
}
In the component in which you have many component imports and registrations
import dynamic_import from '#/services/dynamic_imports' //importing the above file
let components = dynamic_import({
path: 'components/servers',
components: [
{ name: 'server-one', file_name: 'serverOne' },
{ name: 'server-two', file_name: 'serverTwo' },
]
})
export default {
//...other code
components: components
}
As a result you will import and register your components with "clean code".
But note that this worked for me,maybe it has to modified a lit bit to fit your needs,to understand:
The property path means that will look at this path for the names specified in file_name.The name property is the name you register the component
Method 2
If you don't like the above look below to another way:
function import_component(cmp_name){
return System.import(`#/components/${cmp_name}.vue`);
}
export default{
components: {
'component1': () => import_component('componentOne'),
'component2': () => import_component('componentTwo'),
'component3': () => import_component('componentThree')
}
}
Method 3
If again you are saying: This is not a cleaner way,take a look below but keep in mind that if you are working in team and skills differ,then some programmers will be a little bit confused.
dynamic_imports.js
export default function ({path, file_names, component_names}) {
let registered_components = {}
for (let [index, file_name] of file_names.entries()) {
registered_components[component_names[index]] = () => System.import(`../${path}/${file_name}.vue`)
}
return registered_components
}
In your component
import dynamic_import from '#/services/dynamic_imports'
let components = dynamic_import({
path: 'components/servers',
file_names: ['serverOne', 'serverTwo'],
component_names: ['server-one', 'server-two']
})
export default {
components: components
}
You can automatically register such repeated base components globally using the pattern described in the official docs
https://v2.vuejs.org/v2/guide/components-registration.html#Automatic-Global-Registration-of-Base-Components
Chris Fritz also talks about this pattern in his awesome video where he mentions 7 secret patterns for cleaner code and productivity boost while working with Vue.js
The disadvantage of this approach, however, is that the components that you autoregister this way always end up in the main bundle and therefore cannot be lazy loaded/code-splitted. So make sure you do this only for the base components that are very generic.