Using this.$router in a Laravel/Vue.js component - laravel

I have a Vue.js component in Laravel, it's loading with:
Vue.component('user-profile', require('./components/UserProfile.vue').default);
However, when I use this.$router.go() in it, I get the following error:
TypeError: Cannot read property '$router' of undefined
So, I've add this to my routes:
const routes = [
{
path: '/profile',
component: UserProfile
},
...
];
But then, I get:
Uncaught ReferenceError: UserProfile is not defined
So, I replaced:
Vue.component('user-profile', require('./components/UserProfile.vue').default);
by:
import UserProfile from './components/UserProfile.vue';
But I get this error:
Unknown custom element: - did you register the
component correctly?
How should I fix this issue to be able to use this.$router.go() in my component ?
=== EDIT ===
I'm using this.$router.go() here:
methods: {
async update () {
await axios.put(`/api/user/` + this.data.id, this.user)
.then(function (response) {
console.log(response);
this.$router.go()
})
.catch(function (error) {
console.log(error);
});
}
},

Either Use arrow function
methods: {
async update () {
await axios.put(`/api/user/` + this.data.id, this.user)
.then((response) => { // check here
console.log(response);
this.$router.go()
})
.catch((error) => {
console.log(error);
});
}
},
Or use var vm = this;
methods: {
async update () {
var vm = this;// check here
await axios.put(`/api/user/` + this.data.id, this.user)
.then(function (response) {
console.log(response);
vm.$router.go(); // check here
})
.catch(function (error) {
console.log(error);
});
}
},
Read about arrow function

Related

created(){axios.get method is not working when trying to display content from DB

**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',
}
},

React Displaying List of Items from Ajax request

I am learning React and I am trying to display a list of users from and ajax call. I am getting an unexpected token error from CodePen when I add the line
export default Users;
When I remove the line there are no more errors but the list of users is not being displayed.
My code:
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
console.log(data);
callback(null, data);
},
error: function (error) {
console.log(data);
callback(error, {});
}
});
}
function UserList(users) {
const userItems = users.map((user) =>
<ul>
<li>
{ user.name }
</li>
<li>
{ user.email }
</li>
<li>
{ user.phone}
</li>
</ul>
);
return (userItems);
}
class Users extends Component {
componentDidMount() {
GetUsers(null, function (err, data) {
if (err)
{
console.log(err);
}// do something
this.setState({ users: data })
}.bind(this))
}
render() {
return(
<UserList user = {this.state.users} />
);
}
}
if (document.getElementById('root')) {
ReactDOM.render(<Users />, document.getElementById('root'));
}
Here is my code.
Thank you for any and all help!
Problem 1 in AJAX call
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
console.log(data);
callback(null, data);
},
error: function (error) {
console.log(data);
callback(error, {});
}
});
}
$.ajax is asynchronous call, that means it doesn't returns directly any value (how it could if it is fetching the results from the internet) it Just creates another function which will call success and error when completed.
That's why we need to wrap it with callbacks
function GetUsers(project, resolve = () => {}, reject = () => {}) {
}
Problem 2 in mount
componentDidMount() {
GetUsers(null, function (err, data) {
if (err)
{
console.log(err);
}// do something
this.setState({ users: data })
}.bind(this))
}
This code is completely wrong, it has even syntax error so not worth to discuss it in details.
We need to call our new function and pass success callback for mutating the state
GetUsers(null, users => {
this.setState({ users });
});
In this way we will call GetUsers wait for it's results and only after that we will mutate the state with new result
3 problem in component creation
React component's don't have state by default, you need to infer the state from constructor so we need to change initialization to
constructor(props) {
super(props);
this.state = {
users: false
};
}
otherwise you will get Cannot call setState of undefined as state is not automatically created for performance purposes and all components are Pure by default.
I have created a working sandbox here
in
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
return data;
},
error: function (error) {
console.log(error);
return {};
}
});
}
--
success: function (data) {
return data;
}
doesn't do what you think it does. return data isn't really returning the data... anywhere.
You need to have a callback.
function GetUsers(project, callback){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
callback(null, data)
},
error: function (error) {
callback(error, {})
}
});
}
class Users extends Component {
componentDidMount() {
GetUsers(null, function (err, data) {
if (err) // do something
this.setState({ users: data })
}.bind(this))
}
render() {
return(
<UserList user = {this.state.users} />
);
}
}
you can also Promise-ify things to simplify the logic

In My react native app i am not able to setState the ajax response

constructor(){
super();
this.state = {
data: ''
}
}
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
this.setState({data: response }); // here i am getting error
console.log(this.state.data);
})
.catch(function (error) {
console.log(error);
});
In My react native app i am not able to setState the ajax response.. When i am trying to update the state here it throws error and execute catch function... I don't know why it happens can you please give me the quick suggestion
First of all, please read the difference between arrow functions and normal function declarations.
this.setState({}) will only work if you use arrow functions () => or you can do it the old fashion way by saving this inside a variable like so:
fetchData() {
const self = this;
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
self.setState({data: response }); // here i am getting error
console.log(self.state.data);
})
.catch(function (error) {
console.log(error);
});
}
I, however, prefer to use an arrow function instead as it's much simpler.
ex:
fetchData() {
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(response => this.setState({data: response }) )
.catch(console.log);
}
P.S: You can also bind this using the .bind(this) method.
That's because you use the ES2015 syntax to create your function, which doesn't bind the context by default.
Use an arrow function instead :
.then((reponse) => {
console.log(response);
this.setState({data: response });
console.log(this.state.data);
}

TypeError: Cannot set property 'posts' of undefined - Vuejs

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);
});
},
}

vuejs set data value for v2.2.5

So here's my code
var portal = new Vue({
el: "#AnnounceController",
data: {
ann: {
id: '',
content: ''
},
announces: [],
success: false,
edit: false
},
methods: {
fetchAnnounce: function () {
axios.get('/api/announces')
.then(function (response) {
this.announces = response.data;
console.log(this.announces);
})
.catch(function (error) {
console.log(error);
});
}
},
computed: {},
mounted: function () {
console.log('mounted')
this.fetchAnnounce()
}
I have a GET request via axios to a laravel based api, when I look at the response from axios I do see my data, when I try to assign that data to the 'announces' from data, it doesn't work. Vue-devtools shows my data 'announces' attribute as empty, and the log for this.announces shows me my data, somehow like the data attribute for the vue instance and the this.announces are different.
fetchAnnounce: function () {
axios.get('/api/announces')
.then(function (response) {
this.announces = response.data;
console.log(this.announces);
}.bind(this))
.catch(function (error) {
console.log(error);
});
}

Resources