This is my code for my Laravel controller
public function show($postId){
$reaction = Reaction::where([
'post_id' => $postId,
'user_id' => auth()->id(),
])->first();
if ($reaction) {
return response()->json(['isHeart' => true]);
} else {
return response()->json(['isHeart' => false]);
}
}
Code for my Vue.js below
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.head.querySelector('meta[name="csrf-token"]').content;
export default{
data(){
return{
isFilled:false,
isHeart:false,
};
},
created(){
axios.get('/posts/heart-status/${this.postId}')
.then(response =>{
console.log(response.data.isHeart)
this.isFilled = response.data.isHeart;
})
.catch(function (error) {
console.error(error);
})
},
methods:{
toggleFill(){
if(this.isFilled){
this.unheart();
this.isFilled = false;
}else{
this.heart();
this.isFilled = true;
this.isHeart = true
setTimeout(() => {
this.isHeart = false;
}, 1000);
}
},
checkHeartStatus(){
axios.get('/posts/heart-status/${this.postId}')
.then(response =>{
console.log(response.data.isHeart)
this.isFilled = response.data.isHeart;
})
.catch(function (error) {
console.error(error);
})
},
heart(){
axios.post('/posts/heart',{
post_id: this.postId,
})
.then(response =>{
this.isFilled = true;
this.isHeart = true
console.log(response);
})
.catch(error =>{
console.error(error);
});
},
unheart(){
axios.post('/posts/unheart',{
post_id: this.postId
})
.then(response =>{
this.isFilled = false;
this.isHeart = false;
console.log(response);
})
.catch(error =>{
console.error(error);
});
}
},
props: {
postId:{
type: Number,
required: true
}
}
};
</script>
So I want to get a response = true ,in this code but even though it has data it always return false.
And when i go to posts/heart-status/1 it will give me true, but then in the code above with the method created() it will give me false.
already know the problem, instead of using single quotes I use backticks
created(){
axios.get(`/posts/heart-status/${this.postId}`)
.then(response =>{
console.log(response.data.isHeart)
this.isFilled = response.data.isHeart;
})
.catch(function (error) {
console.error(error);
})
},
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'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());
})
**my rout file and when i type directly posts in URL it shows the posts but with created method in app.js it shows nothing **
Route::get('/posts', function () {
$posts_json = DB::table('posts')
->orderBy('posts.created_at','desc')->take(4)->get();return $posts_json;}
My app.js file
const app = new Vue({
el: '#app',
data: {
msg: 'make post',
content:'',
posts: [],
bUrl: 'http://localhost/pathikhome',
},
ready: function(){
this.created();
},
created(){
axios.get(this.bUrl +'/posts')
.then(response => {
console.log(response);
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
methods: {
addPost(){
axios.post(this.bUrl +'/addPost', {
content:this.content
})
if not success
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}});
ready is not supported anymore. That's Vue v1. Your new method is mounted. See https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram and https://v2.vuejs.org/v2/guide/migration.html#ready-replaced
Also data is a function that returns a data object, so if should look like this:
data: function() {
return {
msg: 'make post',
content: '',
posts: []
}
}
remove this.bUrl in the url of your axios:
created(){
axios.get('/posts')
.then(response => {
EDIT:
try to remove the ready function:
ready: function(){
this.created();
},
your data() should have a return inside:
data() {
return{
msg: 'make post',
content:'',
posts: [],
bUrl: 'http://localhost/pathikhome',
}
},
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 : '/' });
}
})
}
I create SPA with VueJs and Laravel.
Homepage i get all posts via api laravel and axio responsive had data object.
But i can not update to posts property.
Error in chrome debug tool:
My code in Wellcome.vue
import { mapGetters } from 'vuex'
import axios from 'axios'
export default {
name: 'welcome',
layout: 'default',
metaInfo: { titleTemplate: 'Welcome | %s' },
computed: mapGetters({
authenticated: 'authCheck'
}),
data: () => ({
title: 'Demo Blog',
}),
props: {
posts: {
type: Object
}
},
created () {
axios.get('/api/posts')
.then(function (response) {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
You are using a regular function as a callback which means this reference changes. You need to use arrow function here . () => {}.
axios.get('/api/posts')
.then((response) => {
this.posts = response.data;
})
.catch((error) => {
console.log(error);
});
First of all you defined posts in your props property. You should not mutate a prop from child component. Props are One-Way-Data-Flow
you can inititialize posts in you data property as follows:
data(){
return{
posts: null
}
}
Then you can fetch data via your API and assign it to your posts in the data property
this in you then function does not point to the vue instance.
So its better you do it like this
created () {
var vm = this;
axios.get('/api/posts')
.then(function (response) {
vm.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
Or you an => function like this
created () {
axios.get('/api/posts')
.then( (response) => {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}