return data object to vue component using laravel 5.6 and axios - laravel-5

I am trying to build an availability carousel. It will show the days of the week, and what time someone is available. I am using Laravel and vue.js. I have done the web api, and I can get the data object following the route
Route::group(['prefix' => '/{area}'], function () {
Route::get('/{tutor}/availability','Tutor\AvailabilityController#show');
});
with this in my availability controller
public function show(Request $request, Area $area, Tutor $tutor)
{
$availability = $tutor->availability()->get();
return response()->json([
'data' => $availability
], 200);
}
That all works.
But when I try and pull it into Vue, nothing shows up. I can't seem to figure out what I might be missing.
I pulled the vue component into blade using the following, and passing in the area and tutor id
<availability area-id="{{ $area->slug }}" tutor-id="{{ $tutor->slug }}">
</availability>
and in Availability.vue, I think where I am going wrong is pulling the data in with props, but I am really not sure anymore.
<script>
$(document).ready(function() {
$("#availability").owlCarousel();
});
export default {
props: {
areaId: null,
tutorId: null
},
data () {
return {
availability: []
}
},
methods: {
getAvailability () {
axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability').then((response) => {
console.log(response.json());
});
}
},
ready () {
this.getAvailability();
}
}
</script>
Thank you for the help.

Axios response object has data field which contains the response from the server. To get the data use
response.data
Also for Vue 2.0 components use mounted instead of ready for when the component is ready. If you are only loading data from the server (and not manipulating the DOM) you can use created instead.
export default {
props: {
areaId: null,
tutorId: null
},
data () {
return {
availability: []
}
},
methods: {
getAvailability () {
var that = this;
axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability')
.then((response) => {
console.log(response.data); // should print {data: availability_object}
// Set this component's availability to response's availability
that.availability = response.data.data;
//OR
//Add response's availability to the components' availability
that.availability.push(response.data.data);
});
}
},
mounted () {
this.getAvailability();
}
}
</script>

Related

Watch Value In Vue.js 3, Equivalent In Pinia?

I have a checkbox list of domain tlds, such as com, net, io, etc. I also have a search text input, where I can drill down the list of 500 or so domains to a smaller amount. For example, if I start to type co in to my search text input, I will get back results that match co, such as co, com, com.au, etc. I am using Laravel and Vue,js 3 to achieve this with a watcher. It works beautifully. How can an achieve the same within a Pinia store?
Here is my code currently:
watch: {
'filters.searchedTlds': function(after, before) {
this.fetchsearchedTlds();
}
},
This is inside my vue component.
Next is the code to fetch searched tlds:
fetchsearchedTlds() {
self = this;
axios.get('/fetch-checked-tlds', { params: { searchedTlds: self.filters.searchedTlds } })
.then(function (response) {
self.filters.tlds = response.data.tlds;
console.log(response.data.tlds);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
},
And finally, the code inside my Laravel controller:
public function fetchCheckedTlds(Request $request)
{
$data['tlds'] = Tld::where('tld', 'LIKE','%'.$request->input('searchedTlds').'%')->pluck('tld');
return response()->json($data);
}
I am converting my code to use a Pinia store and I am stuck on how to convert my vue component watcher to Pinia?
Many thanks in advance.
To watch a pinia status, you may watch a computed attribute based on pinia or use watch getter
Your pinia may look like the one below.
~/store/filters.js
export const useFilters = defineStore('filters', {
state: () => {
return {
_filters: {},
};
},
getters: {
filters: state => state._filters,
},
...
}
In where you want to watch
<script setup>
import { computed, watch } from 'vue';
import { useFilters } from '~/store/filters.js';
const filters = useFilters();
// watch a computed attributes instead
const searchedTlds = computed(() => {
return filters.filters?.searchedTlds || '';
});
watch(
searchedTlds,
(newValue, oldValue) {
fetchsearchedTlds();
}
);
// or use watch getter
watch(
() => {
return filters.filters?.searchedTlds || '';
},
(newValue, oldValue) {
fetchsearchedTlds();
}
);
</script>
The first parameter of watch() can be a single ref or a getter function, or an array of getter functions, for more details, please view the Watch Source Types.

Data not showing on vue.js component using laravel api

I'm trying to get the data from database using an API, but there are no output on my vue controller.
Am I doing this right?
I think I'm assigning the scheduleList the wrong way.
I'm very new to vue.js and API, I want to know what I'm doing wrong here.
Controller
public function schedules(){
return Schedule::all();
}
api.php
Route::get('schedules', 'CalendarController#schedules');
Vue Component
<script>
import axios from 'axios'
export default {
data() {
return {
schedules: [],
scheduleList: [
{
id: schedules.id,
title: schedules.title,
category: schedules.category,
start: schedules.start,
end: schedules.end
},
],
};
},
methods: {
loadSchedules() {
axios.get('/api/schedules')
.then((response) => {
this.schedules = response.data;
})
}
},
mounted() {
this.loadSchedules();
}
};
</script>
<style>
</style>
The issue is in your data option because you're referencing schedules which is undefined, I'm sure that you're meaning this.schedules but doing that will not solve the issue because at first rendering this.schedules is an empty array, another problem that you're referencing at as object in scheduleList items using schedules.id, if the schedules property is an array i recommend the following solution :
<script>
import axios from 'axios'
export default {
data() {
return {
schedules: [],
scheduleList: [],
};
},
methods: {
loadSchedules() {
axios.get('/api/schedules')
.then((response) => {
this.schedules = response.data;
let schedule=this.schedules[0]
this.scheduleList.push({
id: schedule.id,
title: schedule.title,
category: schedule.category,
start: schedule.start,
end: schedule.end
})
})
}
},
mounted() {
this.loadSchedules();
}
};
</script>
always catch errors if you do promises.
loadSchedules() {
axios.get('/api/schedules')
.then((response) => {
this.schedules = response.data;
})
.catch(error => {
console.log(error)
})
inside your error you can better see whats going wrong.
other way is the "network" tab in your browser where you can trace your api request

{{ obj.data }} not displaying in vue template after axios get

I am trying to build a carousel using Laravel 5.6 and Vue.js. I can call the data from db, and console.log response.data. It works like expect it to. Script below.
<script>
$(document).ready(function() {
$("#availability").owlCarousel();
});
export default {
props: {
areaId: null,
tutorId: null,
},
data () {
return {
availability: []
}
},
methods: {
getAvailability () {
var that = this;
axios.get( '/' + this.areaId + '/' + this.tutorId + '/availability').then((response) => {
console.log(response.data)
that.availability = response.data;
});
}
},
mounted () {
this.getAvailability();
}
}
</script>
Now I would expect to be able to display the data like
{{availability.monday_begin}}
but it displays nothing, empty tags.
When I add a second .data to response, so change
that.availability = response.data;
to
that.availability = response.data.data;
The data object shows up as undefined in the vue-dev tools, and {{ availability.monday_begin }} throws an error cannot read property of undefined.
I also tried adding a v-if to the template, based on a couple different articles I read, but nothing I tried worked.
Thanks for your help.

promisse value undefined axios

I'm trying to get values using axios and on my browser returns [[PromisseValue]] undefined. Follow my code. Please, help-me... thanks
This is my data to get
<script>
export default {
props: ['endpoint'],
data () {
return {
response: {
table: '',
displayable: [],
records: []
}
}
},
methods: {
getRecords () {
return axios.get(`${this.endpoint}`).then((response) => {
console.log(response.data.data.table)
})
}
},
mounted () {
this.getRecords()
}
}
It will return promise because AXIOS is a promise function that you are trying to return.
axios.get(`${this.endpoint}`).then((response) => {
this.response.table = response.data.data.table
})
after axios call you need save it into your state or data the response then use it wherever you want.

How to load AJAX in react

Im trying to get my json result into my react code
The code looks like the following
_getComments() {
const commentList = "AJAX JSON GOES HERE"
return commentList.map((comment) => {
return (
<Comment
author={comment.author}
body={comment.body}
avatarUrl={comment.avatarUrl}
key={comment.id} />);
});
}
How do i fetch AJAX into this?
First, to fetch the data using AJAX, you have a few options:
The Fetch API, which will work out of the box in some browsers (you can use a polyfill to get it working in other browsers as well). See this answer for an example implementation.
A library for data fetching (which generally work in all modern browsers). Facebook recommends the following:
superagent
reqwest
react-ajax
axios
request
Next, you need to use it somewhere in your React component. Where and how you do this will depend on your specific application and component, but generally I think there's two scenarios to consider:
Fetching initial data (e.g. a list of users).
Fetching data in response to some user interaction (e.g. clicking a
button to add more users).
Fetching initial data should be done in the life-cycle method componentDidMount(). From the React Docs:
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
lastGistUrl: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Here they use jQuery to fetch the data. While that works just fine, it's probably not a good idea to use such a big library (in terms of size) to perform such a small task.
Fetching data in response to e.g. an action can be done like this:
var UserGist = React.createClass({
getInitialState: function() {
return {
users: []
};
},
componentWillUnmount: function() {
this.serverRequest && this.serverRequest.abort();
},
fetchNewUser: function () {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
var users = this.state.users
users.push(lastGist.owner.login)
this.setState({ users });
}.bind(this));
},
render: function() {
return (
<div>
{this.state.users.map(user => <div>{user}</div>)}
<button onClick={this.fetchNewUser}>Get new user</button>
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
mountNode
);
Lets take a look on the fetch API : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Lets say we want to fetch a simple list into our component.
export default MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
lst: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
fetch('url')
.then((res) => {
return res.json();
})
.then((res) => {
this.setState({ lst: res });
});
}
}
We are fetching the data from the server, and we get the result from the service, we convert is to json, and then we set the result which will be the array in the state.
You can use jQuery.get or jQuery.ajax in componentDidMount:
import React from 'react';
export default React.createClass({
...
componentDidMount() {
$.get('your/url/here').done((loadedData) => {
this.setState({data: loadedData});
});
...
}
First I'd like to use fetchAPI now install of ajax like zepto's ajax,the render of reactjs is asyn,you can init a state in the constructor,then change the state by the data from the result of fetch.

Resources