I'm trying to use the dispatch function in vue.js like this.
But I'm getting an error saying this2.$dispatch is not a function...like you can see on the screenshot
message.vue
export default {
data(){
return{
message:'',
isLoading:false,
}
},
methods:{
addMessage(){
if(this.message !=''){
this.sendData();
} else{
this.$fire({
title: "Error",
text: "Enter some text.",
type: "error",
timer: 3000
}).then(r => {
console.log(r.value);
});
setTimeout(() => {
this.isLoading = false
},700)
}
},
sendData(){
this.isLoading = true;
this.$http.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms}).then((response) => {
console.log(response.json());
if(response.body != 'Error'){
this.message = '';
this.$dispatch('new_message', response.json());
} else{
this.isLoading = false;
}
}, (response) =>{
});
}
}
}
and then I'm trying to get it out like this
chat.vue
export default {
components:{
get_message:getMessage,
add_message:addMessage,
},
data(){
return{
messages:[]
}
},
events:{
'new_message':function(data){
this.messages.push(data);
}
}
}
I'm facing this error in console...any ideas how can I solve this ?
update
If your store is registered with Vue, it seems like it should work. If your $dispatch works outside of the promise, you can try storing this context in another variable
sendData(){
this.isLoading = true;
const that = this;
this.$http
.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms})
.then((response) => {
console.log(response.json());
if(response.body != 'Error'){
that.message = '';
that.$dispatch('new_message', response.json());
} else{
that.isLoading = false;
}
}, (response) =>{
});
}
or just the $dispatch
sendData(){
this.isLoading = true;
const $dispatch = this.$dispatch;
this.$http
.post('/add-message' , {message:this.message, id_rooms:this.$route.params.id_rooms})
.then((response) => {
console.log(response.json());
if(response.body != 'Error'){
this.message = '';
$dispatch('new_message', response.json());
} else{
this.isLoading = false;
}
}, (response) =>{
});
}
Taking a guess here, but try calling this instead
this.$store.dispatch('new_message', response.json());
alternatively, your issue could be a scope issue (seeing that this is called from a promise)
if you have a function declared like this in the promise handler then(function(response){this.$store.dispatch('new_message', response.json());}) it might be due to scope
instead you could try using arrow function
then((response) => {
this.$store.dispatch('new_message', response.json());
})
Related
My reducer file is below
const slice = createSlice({
name: "hotels",
initialState: {
list: [],
loading: false,
lastFetch: null,
},
reducers: {
hotelsRequested: (hotels) => {
hotels.loading = true;
},
hotelsRequestFailed: (hotels) => {
hotels.loading = false;
},
hotelsReceived: (hotels, action) => {
hotels.list = action.payload;
hotels.loading = false;
hotels.lastFetch = Date.now();
},
hotelEnabled: (hotels, action) => {
const { slug } = action.payload;
const index = hotels.list.findIndex((hotel) => hotel.slug === slug);
hotels.list[index].active = true;
},
},
});
export const {
hotelsReceived,
hotelsRequestFailed,
hotelsRequested,
hotelEnabled,
} = slice.actions;
export default slice.reducer;
//Action creators
export const loadHotels = () => (dispatch, getState) => {
const { lastFetch } = getState().entities.hotels;
const diffInMinutes = moment().diff(lastFetch, "minutes");
if (diffInMinutes < 10) return;
dispatch(
hotelApiCallBegan({
url: hotelUrl,
onStart: hotelsRequested.type,
onSuccess: hotelsReceived.type,
onError: hotelsRequestFailed.type,
})
);
};
export const enableHotel = (slug) =>
hotelApiCallBegan(
{
url: `${hotelUrl}${slug}/partial-update/`,
method: "put",
data: { active: true },
onSuccess: hotelEnabled.type,
},
console.log(slug)
);
My api request middleware function is as follows
export const hotelsApi = ({ dispatch }) => (next) => async (action) => {
if (action.type !== actions.hotelApiCallBegan.type) return next(action);
const {
onStart,
onSuccess,
onError,
url,
method,
data,
redirect,
} = action.payload;
if (onStart) dispatch({ type: onStart });
next(action);
try {
const response = await axiosInstance.request({
baseURL,
url,
method,
data,
redirect,
});
//General
dispatch(actions.hotelApiCallSuccess(response.data));
//Specific
if (onSuccess) dispatch({ type: onSuccess, payload: response.data });
} catch (error) {
//general error
dispatch(actions.hotelApiCallFailed(error.message));
console.log(error.message);
//Specific error
if (onError) dispatch({ type: onError, payload: error.message });
console.log(error.message);
}
};
Could anyone point me in the right direction of how to add an optimistic update reducer to this code. Currently on hitting enable button on the UI there's a lag of maybe second before the UI is updated. Or maybe the question, is do i create another middleware function to handle optimistic updates? If yes how do i go about that? Thanks
I try to set up plugin ckeditor/ckeditor5-export-pdf on my Laravel App But I cant do this. I still get issues like: Uncaught TypeError: Failed to resolve module specifier "#ckeditor/ckeditor5-export-pdf/src/exportpdf". Relative references must start with either "/", "./", or "../".
I did all steps as in docs: https://ckeditor.com/docs/ckeditor5/latest/features/export-pdf.html#configuration But when I try use import ExportPdf from '#ckeditor/ckeditor5-export-pdf/src/exportpdf'; I get the error like above. Please help. Maybe some have stuck on this issue before
import ExportPdf from '#ckeditor/ckeditor5-export-pdf/src/exportpdf';
console.log(ExportPdf);
$(document).ready(function () {
/*function ExportPdf(editor) {
editor.execute('exportPdf');
}*/
function SimpleUploadAdapter(editor) {
editor.plugins.get('FileRepository').createUploadAdapter = function(loader) {
return {
upload: function() {
return loader.file
.then(function (file) {
return new Promise(function(resolve, reject) {
// Init request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/admin/instructions/ckmedia', true);
xhr.setRequestHeader('x-csrf-token', window._token);
xhr.setRequestHeader('Accept', 'application/json');
xhr.responseType = 'json';
// Init listeners
var genericErrorText = `Couldn't upload file: ${ file.name }.`;
xhr.addEventListener('error', function() { reject(genericErrorText) });
xhr.addEventListener('abort', function() { reject() });
xhr.addEventListener('load', function() {
var response = xhr.response;
if (!response || xhr.status !== 201) {
return reject(response && response.message ? `${genericErrorText}\n${xhr.status} ${response.message}` : `${genericErrorText}\n ${xhr.status} ${xhr.statusText}`);
}
$('form').append('<input type="hidden" name="ck-media[]" value="' + response.id + '">');
resolve({ default: response.url });
});
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
loader.uploadTotal = e.total;
loader.uploaded = e.loaded;
}
});
}
// Send request
var data = new FormData();
data.append('upload', file);
data.append('crud_id', {{ $instruction->id ?? 0 }});
xhr.send(data);
});
})
}
};
}
}
var allEditors = document.querySelectorAll('.ckeditor');
for (var i = 0; i < allEditors.length; ++i) {
ClassicEditor.create(
allEditors[i], {
extraPlugins: [SimpleUploadAdapter, /*ExportPdf*/],
/*toolbar: [
'exportPdf', '|',
],
exportPdf: {
stylesheets: [
'./path/to/fonts.css',
'EDITOR_STYLES',
'./path/to/style.css'
],
fileName: 'my-file.pdf',
converterOptions: {
format: 'A4',
margin_top: '20mm',
margin_bottom: '20mm',
margin_right: '12mm',
margin_left: '12mm',
page_orientation: 'portrait'
}
}*/
}
);
}
});
</script>```
I solved my problem with https://ckeditor.com/ckeditor-5/online-builder/ Builded what I want and setup it on my App
I have a modal where I can create edit users. But when I click on the submit button I got a 401 error.
and I want to change the name without update page
The method looks like this:
if(token){
this.preformUpdate();
}
},
methods: {
preformUpdate: function() {
this.loading = true;
this.msgupdate = "Updated your profile";
this.alert = true;
axios
.patch("/profile", {
name: this.name,
token: this.token
})
.then(response => {
const name = localStorage.setItem("name", response.data.user.name);
this.email = localStorage.getItem("email");
console.log(response.data.user.name);
this.loading = false;
})
.catch(error => {
console.log(error);
this.error = error.message;
this.loading = false;
});
}
}
i have created login with rest-full api login system with vue 2 laravel
i want after login it should redirect to another page like /
i have tried with add then redirect: '/'
here is my script
<script>
export default {
data(){
return{
loginDetails:{
email:'',
password:'',
remember:true
},
errorsEmail: false,
errorsPassword: false,
emailError:null,
passwordError:null
}
},
methods:{
loginPost(){
let vm = this;
axios.post('/login', vm.loginDetails)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
var errors = error.response
if(errors.statusText === 'Unprocessable Entity'){
if(errors.data){
if(errors.data.email){
vm.errorsEmail = true
vm.emailError = _.isArray(errors.data.email) ? errors.data.email[0]: errors.data.email
}
if(errors.data.password){
vm.errorsPassword = true
vm.passwordError = _.isArray(errors.data.password) ? errors.data.password[0] : errors.data.password
}
}
}
});
}
},
mounted() {
}
}
this may help
loginPost(){
axios.post('/login', this.loginDetails)
.then(function (response) {
if(response.status === 200) {
this.$router.push({ path : '/' });
}
})
}
In app.js -> methods i have this.chat.image.push(''); and in axios.post send i have
methods:{
send(){
if(this.message.length != 0)
{
this.chat.message.push(this.message);
this.chat.user.push('');
this.chat.image.push('');
this.chat.time.push('');
axios.post('admin/send', {
message : this.message,
chat:this.chat
})
.then(response => {
// console.log(response);
this.message = '';
})
}
},
getOldMessages(){
axios.post('admin/getOldMessage')
.then(response => {
if (response.data != '') {
this.chat = response.data;
}
})
},
And in mounted() i have
mounted(){
this.getOldMessages();
Echo.channel('chat')
.listen('ChatEvent', (e) => {
this.chat.message.push(e.message);
this.chat.user.push(e.user);
this.chat.image.push('source/admin/assets/images/avatar/'+e.image);
axios.post('admin/saveToSession',{
chat : this.chat
.then(response => {
console.log(response);
})
})
})
}
In Controller i have function saveToSession
public function saveToSession(request $request)
{
session()->put('chat',$request->chat);
}
In send() function i get image=" "; but when I save to the session it returns null, How come it returns to the value = " " ? Thanks
Check that value in $request->chat are coming properly or not if yes then you can try other methods as well
Via a request instance
$request->session()->put('key', 'value');
Via the global helper
session(['key' => 'value']);