How can I call a method within mutation method using VueJS 2? - javascript

I got a problem here. I don't know how to call a method within mutation method, I've tried this.show() but it doesn't work, is there's a way like actions in vuex that you can call a method within the action using dispatch ?
// Mutation
export default {
show(state, payload) {
// execute code
},
hide(state, payload) {
// how to call show method?
}
}
I want mutation look like this
// Action
export default {
show({ state }, payload) {
// execute code
},
hide({ dispatch, state }, payload) {
// how to call show method look like this in mutation?
// Is this possible for mutation?
return dispatch('show', payload)
}
}

In VueJS 2 you should use $emit instead of $broadcast as described in documentation - https://v2.vuejs.org/v2/guide/migration.html#dispatch-and-broadcast-replaced

Related

Vue.js component method on creation

I'm new to Vue and I'd like to make an AJAX call every time my component is rendered.
I have a vue component lets say "test-table" and Id like to fetch the contents via an AJAX call. There are many such tables and I track the active one via an v-if/v-else-if etc.
Currently I have a cheaty solution: in the template for the component I call a computed property called getData via {{ getData }} which initiates the Ajax call but does only return an empty string. Id like to switch to the proper way but dont know how.
My code is like so: (its typescript)
Vue.component("test-table", {
props: ["request"],
data () {
return {
tableData: [] as Array<TableClass>,
}
},
template: `{{ getData() }} DO SOME STUFF WITH tableData...`,
computed: {
getData() : string {
get("./foo.php", this.request, true).then(
data => this.tableData = data.map(element => new TableClass(data))
)
return "";
}
}
}
HTML:
<test-table v-if="testcounter === 1" :request="stuff...">
<test-table v-else-if="testcounter === 2" :request="other stuff...">
...
get is an async method that just sends a GET request with request data to the server. The last parameter is only for saying the method to expect a JSON as answer. Similar to JQuerys getJSON method.
the "created" method does NOT work! It fires only one time when the component is first created. If I deactivate and activate again (with v-if) the method is not called again.
Btw: I'm using Vue 2.6.13
Lifecycle hooks won't fire every time if the component is cached, keep-alive etc
Add a console.log in each of the lifecycle hooks to see.
Change to use a watcher which handles firing getData again if request changes.
...
watch: {
request: {
handler: function() {
this.getData()
},
deep: true
}
},
created() {
this.getData()
},
methods: {
getData(): string {
// do request
}
}
#FlorianBecker try the lifecycle hook updated(). It may be a better fit for what you're trying to achieve. Docs here.
You should be able to use the mounted hook if your component is continuously rendered/unrendered using v-if, like so:
export default {
mounted() {
// do ajax call here
this.callAMethod();
},
...
}
Alternatively, you could use the created() hook but it is executed earlier in the chain, so this means the DOM template is not created yet so you cant refer to it. mounted usually is the way to go.
More info on these hooks can be found here.

Best practise to handle with responses and incoming props

with redux, we uses actions to handle with crud operations. But I stuck at some points. If we send async requests inside of component. We can easly handle with response. But when we send request through actions, we dont know what happened. Is request send successfully ? it took how much amount of time ? What kind of response is returned ? we don't know that
I will clarify question with samples..
lets update a post.
onClick () {
postsApi.post(this.state.post) | we know how much time
.then(res => res.data) | has took to execute
.then(res => { | request
console.log(res) // we have the response
})
.catch(err => console.log(error))
}
But if we use actions
onClick () {
this.props.updatePost(this.state.post) // we know nothing what will happen
}
or handling with incoming props. lets say I have fetchPost() action to retrieve post
componentDidMount(){
this.props.fetchPost()
}
render method and componentDidUpdate will run as well. It's cool. But what if I want to update my state by incoming props ? I can't do this operation inside of componentDidUpdate method. it causes infinity loop.
If I use componentWillUpdate method, well, things works fine but I'm getting this warning.
Warning: componentWillReceiveProps has been renamed, and is not
recommended for use. Move data fetching code or side effects to
componentDidUpdate. If you're updating state whenever props change,
refactor your code to use memoization techniques or move it to static
getDerivedStateFromProps
I can't use componentDidUpdate method for infinty loop. Neither getDerivedStateFromProps method because it's run everytime when state change.
Should I continue to use componentWillMethod ? Otherwise what should I use and why (why componentWillMethod is unsafe ?)
If I understand correcty, what you would like to do is to safely change your local state only when your e.g. updatePost was successful.
If indeed that is your case, you can pass a callback function on your updatePost and call this as long as your update was succefull.
successfulUpdate() {
// do your thing
this.setState( ... );
}
onClick () {
this.props.updatePost(this.state.post, this.successfulUpdate) // we know nothing what will happen
}
UPDATE:
You can also keep in mind that if your action returns a promise, then you can just use the then method:
onClick () {
this.props.updatePost(this.state.post).then(this.onFulfilled, this.onRejected)
}
I think we can use redux-thunk in this cases. What if we dispatch an async function instead of dispatch an action object?
"Neither getDerivedStateFromProps method because it's run everytime when state change." - does it matter? You can avoid setting state with every getDerivedStateFromProps call by using a simple condition inside.
Example:
static getDerivedStateFromProps(props, state) {
if (props.post !== state.post) { // or anything else
return {
post: props.post,
};
}
return null;
};
An infinite loop will not occur.
Here is my way for such cases. We can redux-thunk for asynchronous calls such as api call. What if we define the action that returns promise? Please check the code below.
actions.js
export const GetTodoList = dispatch => {
return Axios.get('SOME_URL').then(res => {
// dispatch some actions
// return result
return res.data;
});
}
TodoList.js
onClick = async () => {
const { GetTodoList } = this.props;
try {
const data = await GetTodoList();
// handler for success
this.setState({
success: true,
data
});
} catch {
// handler for failure
this.setState({
success: fail,
data: null
});
}
}
const mapStateToProps = state => ({
GetTodoList
});
So we can use actions like API(which returns promise) thanks to redux-thunk.
Let me know your opinion.

Passing parameters to Vuex getters from a Vuex action

I have a Vuex getter that I call from various components in my application. However, I have found a case were slightly more complex logic is required before calling the getter, so I am making use of a Vuex Action. How can I call the getter function with a parameter from my action?
I use constants for naming getters/mutations/actions, so my getter is defined as follows: [GETTER_NAME]: state => param => { return {/.../} }. In my Vuex action, I would like to call the getter as follows getters[GETTER_NAME](someParam). However, this does not seem to work (even though getters[GETTER_NAME] returns a function).
Calling the getter from a component works perfectly fine. I simply create computed function and use ...mapGetters({getterName: GETTER_NAME}). To call the getter with a parameter I just say getterName(someParam).
[GETTER_NAME]: state => param=> {
return {/.../}
},
[ACTION_NAME]: (context, param) => {
getters[GETTER_NAME](param)
? context.commit(MUTATION_X, param)
: context.commit(MUTATION_Y, param);
}
The getter gets called, however, it returns the function without passing in the parameter. Am I doing something wrong or am I misunderstanding the way getters work in Vuex?
You need to call like context.getters[GETTER_NAME](someParam) inside actions here.
[GETTER_NAME]: state => param=> {
return {/.../}
},
[ACTION_NAME]: (context, param) => {
context.getters[GETTER_NAME](param)
? context.commit(MUTATION_X, param)
: context.commit(MUTATION_Y, param);
}
In actions have injected parameters : dispatch, commit, getters and rootState. Therefore you can access getters like this:
ACTION_NAME: ({ commit, getters }, payload) => {
let MY_VARIABLE = getters.GETTER_NAME(payload)
console.log(MY_VARIABLE)
}
This works fine even if you try to access a getter from a different module.
Though you can use getters with context via context.getters the syntax gets a bit longish inside the action when using it this way.

Should mapDispatchToProps dispatch initialization actions?

Suppose a stateless, functional UserProfile component that displays user data for the given url. Suppose it is being wrapped with connect(mapStateToProps, mapDispatchToProps)(UserProfile). Finally, suppose a reducer that reduces into state.userProfile. Anytime the url changes, I need to re-initialize the state.userProfile, so a solution that comes to mind is to do so from within the mapDispatchToProps like so:
function mapDispatchToProps(dispatch, ownProps) {
dispatch(fetchUser(ownProps.userId))
return {
...
}
}
Provided that the thunked fetchUser ignores repeated calls by comparing with current state, is this an acceptable practice? Or are there problems associated with calling dispatch immediately from this map function?
This is unsupported and can break at any time.
mapDispatchToProps itself should not have side effects.
If you need to dispatch actions in response to prop changes, you can create a component class and use lifecycle methods for this:
class UserProfile extends Component {
componentDidMount() {
this.props.fetchUser(this.props.id)
}
componentDidUpdate(prevProps) {
if (prevProps.id !== this.props.id) {
this.props.fetchUser(this.props.id)
}
}
// ...
}

how can i create a helper type function in my redux module to return a filtered set of readonly data from state?

Using redux, I am trying to write a "helper function" in my redux module which returns filtered data from state based on what index i pass into it. This data is used to build out a form of inputs based on whether auth: true or budt: true. The form basically would iterate over all totypes for that level and conditionally show/hide the auth or budt inputs.
Given the state...
totypesmap: [
{
level:1,
totypes:[
{ttno:1, ttcode:'', ttdesc:'regular', auth:true, budt:false},
]
}
]
I have a function exported in my module that expects an index argument and returns its appropriate totypesmap[index] from state. However in order to get to state from within it i have to use getState() which expects a Promise to be resolved with its data I am assuming.
Should i be accomplishing this some other way?
export const MyTOTypes = (level) => {
return (dispatch, getState) => {
const state = getState()
// return state.masterdata.totypesmap[level].totypes
}
}
In my container or component I simply import { MyTOTypes } from 'redux/modules/masterdata' and then call it whenever i need to know the TO Types assigned to my "level" MyTOTypes(0)
If the data is constant, don't put it in the redux store. Just put it in a module and expose your helper methods to retrieve the data.
const totypesmap = [ ... ];
export function MyToTypes(level) { return totypesmap[level].totypes; }
If you really want it in the Redux store, then have your method take state as the first argument. Your React components will be calling this method from within their mapStateToProps method and will have the store state available:
export function MyToTypes(state, level) { return state.totypesmap[level].totypes; }

Categories

Resources