I need to change lang value on export const GetWeatherDetails = ( location ="Paris", lang= 'en'), what would be the proper way to do it, it's an Action.js file so I need to get it done from App.js or another file in this case I got Weather.js
export const GetWeatherDetails = ( location ="Paris", lang= 'en') => async dispatch => {
dispatch({ type: GET_WEATHER.PENDING });
axios
.get(BASE_URL, {
params: {
q: location,
lang: lang,
units: "Metric",
}
})
.then(response =>
dispatch({ type: GET_WEATHER.SUCCESS, payload: response.data })
)
.catch(err => {
console.log(err.response, err);
toast.error(err.response.data.message, {
position: "bottom-center",
autoClose: 2000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: false,
draggable: false
});
dispatch({ type: GET_WEATHER.REJECTED, payload: err.response });
});
};
As #IronGeek pointed out, lang is the second argument to the GetWeatherDeatils function. It's predefined with the "en", so that if you call GetWeatherDetails without the second argument, "en" is used. For example:
GetWeatherDetails('Berlin')
If you want to pass in another value, just call GetWeatherDetails with other values:
GetWeatherDetails('Berlin', 'de')
You can read more about default function arguments at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
Related
When passing some "query options" while using useQueries() to fetch multiples queries at the same time, these "query options" are not been applied on any query execution (eg: refetchOnWindowFocus is true and I want it to be false).
Example
const slidesID = ['11111', '22222', '33333'];
const COMMON_QUERY_OPTIONS = {
retry: false,
refetchOnWindowFocus: false,
refetchOnMount: false,
} as const;
const slideQueries = useQueries(
slidesID.map((slideID) => {
return {
queryKey: ['slides', 'slide', slideID],
queryFn: () => getSlide(slideID),
COMMON_QUERY_OPTIONS,
};
}),
);
The problem is you are passing in the WRONG way the "query options".
There are two similar but different ways of executing useQuery:
a) common way ( just the 3er param is an {object} )
const result = useQuery(queryKey,queryFn, {
retry: false,
refetchOnWindowFocus: false,
refetchOnMount: false,
} )
b) the object syntax way (all the params are at the same level inside a global object)
const result = useQuery({queryKey, queryFn, retry: false,
refetchOnWindowFocus: false,
refetchOnMount: false,
})
In your example, you are using the 'the object syntax way' but passing the "query options" as the 'common way'. To fix it just apply a ...spread to correctly pass the options.
FIXED Example
const slidesID = ['11111', '22222', '33333'];
const COMMON_QUERY_OPTIONS = {
retry: false,
refetchOnWindowFocus: false,
refetchOnMount: false,
} as const;
const slideQueries = useQueries(
slidesID.map((slideID) => {
return {
queryKey: ['slides', 'slide', slideID],
queryFn: () => getSlide(slideID),
...COMMON_QUERY_OPTIONS, //notice the ... here
};
}),
);
I have function in setup() named onRquest, I want to call that function in methods after execution of an action(deleting row), which gonna refresh the table. Please check the code segment for better understanding:
export default {
setup() {
function onRequest(props) {
}
onMounted(() => {
onRequest({
pagination: pagination.value,
filter: undefined,
})
})
return {
onRequest
}
},
methods: {
deleteBranch(branch_id) {
this.$q.dialog({
title: 'Confirm',
message: 'Would you like to Delete Branch#' + branch_id + '?',
cancel: true,
persistent: true
}).onOk(() => {
this.$axios.delete('https://api.bdshsystem.com/api/v1/branch/' +
branch_id).then(response => {
this.$q.notify({
type: 'positive',
timeout: 500,
position: 'top',
message: 'Branch Deleted Successfully !'
})
I want to put function onRequest Here
}).catch((error) => {
this.$q.notify({
type: 'negative',
position: 'top',
timeout: 500,
message: 'Form submission Failed !'
})
})
}).onOk(() => {
// console.log('>>>> second OK catcher')
}).onCancel(() => {
// console.log('>>>> Cancel')
}).onDismiss(() => {
// console.log('I am triggered on both OK and Cancel')
})
},
},
}
Insted of passing you method inline i.e. the "setup()" method, directly in export default. define it outside and pass its reference to export default then you can call setup() directly in whatever method you want
function setup(){
//some code
}
export default {"setup":setup,
"yourOtherMethod":function yourOtherMethod(){
//your other method code here
}}
I just need some help identifying what I am missing here. Just can't seem to send the correct data through:
Parent with the CommunicationPreference component:
<CommunicationPreference
v-for="(communication, index) in communicationPreference"
:key="index"
:consent="communication.consent"
:name="communication.name"
#update="updateConsent(consent)"
/>
METHOD
methods: {
async updateConsent(consent) {
await this.$store.dispatch('account/updateCommunicationPreferences', { consent })
},
},
CommunicationPrefernce.vue
<Button
class="mr-4"
:text="YES"
:type="consent === true ? 'primary' : 'secondary'"
#clicked="updateConsent(true)"
/>
<Button
:text="NO"
:type="consent !== true ? 'primary' : 'secondary'"
#clicked="updateConsent(false)"
/>
PROPS:
props: {
type: {
type: String,
default: '',
},
name: {
type: String,
default: '',
},
consent: {
type: Boolean,
default: true,
},
},
METHOD:
updateConsent(consent) {
this.$emit('update', consent)
},
STORE:
async updateCommunicationPreferences({ commit, state }, payload) {
const { consent } = payload
const { communicationTypeName } = state.communicationTypeName
try {
const response = await this.$axios.put(`/communication-consent/${communicationTypeName}`, consent)
const { data: updatedCommunicationPreferences } = response.data
commit('SET_UPDATED_COMMUNICATION_PREFERENCES', updatedCommunicationPreferences)
} catch (error) {
commit('ADD_ERROR', { id: 'updateCommunicationPreferences', error }, { root: true })
}
},
Attached is the UI I am working towards for reference. the idea is each time the user selects either YES or NO the selection is updated and reflected on the UI
Here is my Swagger doc:
I assume that you have a mapped getter for communicationPreference prop, so that this is correct.
I also assume that your #clicked event prop is proper provided the implementation of Button.vue.
So try to change #update="updateConsent(consent)" to #update="updateConsent"
Right now it seems to me that you are making a small mistake between a function call and declaration. Having it such as #update="updateConsent" will trigger updateConsent method, and the function declaration:
async updateConsent(consent) {
await this.$store.dispatch('account/updateCommunicationPreferences', { consent })
},
will take care of getting the consent you pass in your event trigger.
I am trying to write a react code to submit the value to the backend server.
I want the input field to be cleared out as soon as the user hits submit button.
I have written the below code, could anyone help me with what I am missing here?
class Create extends Component {
state = {
task : {
title: '',
completed: false
}
}
CreateHandler = (event) => {
this.setState((state) => {
return {
task: {
...state, title: '' // <----- CLEARING HERE (well, trying)
}
}
});
event.target.value=""; // <----- ALSO HERE
event.preventDefault();
axios({
method:'post',
url:'http://localhost:8000/api/task-create',
data: this.state.task,
xsrfHeaderName: this.props.CSRFToken
})
.then((res) => {
console.log(res.data);
})
this.props.updateState(this.state.task)
}
ChangeHandler = (event) => {
this.setState(state => {
return {
task: {
...state, title: event.target.value
}
}
})
}
Breaking the code in parts so that it's easily readable.
render() {
return (
<form onSubmit={this.CreateHandler.bind(this)}>
<div className="header form-group">
<input
className="newItem form-control"
onChange={this.ChangeHandler.bind(this)}
value={this.state.task.title}
/>
<button
type="submit"
class="saveButton btn btn-primary btn-warning">
submit
</button>
</div>
</form>
)
}
}
export default Create;
The end goal is to clear the input field and then send the data to the backend django server, which is being done successfully except the input field being cleared.
You are not updating state correctly
this.setState((state) => {
return {
task: {
...state, title: '' // <----- CLEARING HERE (well, trying)
}
}
});
should be
this.setState((state) =>({...state, task: {...state.task, title: ''}}))
In your case, it could be done like this:
this.setState(previousState => ({
task: {
...previousState.task,
title: '' // <----- CLEARING HERE
}
}));
A better way to write your createHandler method:
CreateHandler = (event) => {
// Prevent the default form action
event.preventDefault();
// Call your API
axios({
method: "post",
url: "http://localhost:8000/api/task-create",
data: this.state.task,
xsrfHeaderName: this.props.CSRFToken,
}).then((res) => {
// Request passed
// Call your prop function
this.props.updateState(this.state.task);
// Clear the unnecessary data
this.setState((prevState) => ({
// Create new object
task: {
// Assign the properties of previous task object
...prevState.task,
// Clear the title field
title: "",
},
}));
});
};
Hope this helps!
I'm using vuex to manage the state in my application and doing one way binding with my form.
<script>
import { mapGetters } from 'vuex'
import store from 'vuex-store'
import DataWidget from '../../../../uiComponents/widget'
export default {
data () {
return {
isEdit: false,
msg: {
id: 0,
content: '',
isEnabled: false
}
}
},
components: {
DataWidget
},
computed: mapGetters({
messageId: 'messageId',
messageContent: 'messageContent',
isMessageEnabled: 'isMessageEnabled',
isMessageValid: 'isMessageValid'
}),
methods: {
onSave () {
store.dispatch('saveMessage', this.msg, { root: true })
if (this.isMessageValid) {
this.isEdit = !this.isEdit
}
}
},
created () {
this.msg.id = this.messageId
this.msg.content = this.messageContent
this.msg.isEnabled = this.isMessageEnabled
}
}
</script>
<b-form-textarea id="content" v-model="msg.content" :rows="3" required aria-required="true" maxlength="250"></b-form-textarea>
On load, the values on created() are not binded until I perform an action on the page or refresh the page.
I have tried mounted () hooked same thing.
My Vuex store (Message Module) looks like this:
const state = {
messageId: 0,
messageContent: '',
isMessageEnabled: false,
isMessageValid: true
}
const getters = {
messageId: state => state.messageId,
messageContent: state => state.messageContent,
isMessageEnabled: state => state.isMessageEnabled,
isMessageValid: state => state.isMessageValid
}
const actions = {
getMessage ({commit, rootGetters}) {
api.fetch('api/Preference/Message', rootGetters.token)
.then((data) => {
commit(types.MESSAGE_LOAD, data)
})
}
}
const mutations = {
[types.MESSAGE_LOAD] (state, payload) {
state.messageId = payload ? payload.id : 0
state.messageContent = payload ? payload.content : ''
state.isMessageEnabled = payload ? payload.enabled : false
}
}
export default {
state,
getters,
actions,
mutations
}
and I have a global action (action.js) the gets multiple data:
export const loadSetting = ({ commit, rootGetters }) => {
api.fetchAsync('api/Preference/all', rootGetters.token)
.then((data) => {
commit(types.MESSAGE_LOAD, data.message)
commit(types.HELPDESK_LOAD, data.helpDesk)
commit(types.VOLUME_LOAD, data.volumes)
commit(types.DOWNLOAD_LOAD, data.downloadService)
})
}
My api call:
async fetchAsync (url, token = '') {
let data = await axios.get(HOST + url, {
headers: {
'Authorization': 'bearer ' + token
}
})
return data
}
The problem is your'e calling an async method in Vuex but in the created method, you're treating it like a sync operation and expect to get a value.
You need to use the computed properties you created since they are reactive and will update on every change. In order to make the computed writeable change it to be like this:
computed: {
...mapGetters({
messageId: 'messageId',
isMessageEnabled: 'isMessageEnabled',
isMessageValid: 'isMessageValid'
}),
messageContent(){
get () {
return this.$store.getters.messageContent
},
set (value) {
//this is just an example, you can do other things here
this.$store.commit('updateMessage', value)
}
}
}
And change the html to use messageContent:
<b-form-textarea id="content" v-model="messageContent" :rows="3" required aria-required="true" maxlength="250"></b-form-textarea>
For more info refer to this: https://vuex.vuejs.org/en/forms.html