Print data from axios - laravel

I try to print data from axios.
In controller:
public function index()
{
return User::latest();
}
In user.vue:
export default {
data() {
return {
users: {},
}
},
methods: {
loadUsers() {
axios.get('/user').then(({ data }) => (this.users = user))
console.log(user)
},
},
created() {
this.loadUsers()
},
}
And table:
<tr v-for="user in users.data" :key="user.id">
<td>{{user.email}}</td>
</tr>
Web
Route::get('/user','UserController#index');
console.log prints the data, but in table no data.

axios call async call so make a promise call .then() after fetching data it will call and you can make usable the fetched data.
import axios from "axios";
const API_URL = "http://192.168.1.26:8000";
export class BaseStatus_Service {
getBaseStatus_list() {
const url = `${API_URL}/api/baf1/baseStatus`;
return axios.get(url).then(response => response.data);
}
const serviceUtil = new BaseStatus_Service();
serviceUtil.getBaseStatus_list().then((results)=>{
console.log(results);
})

Related

Cannot destructure property of {intermediate value} as it is undefined

I have just started using graphql for the first time as I have integrated my NEXTJS app with strapi. But I have received this error message Cannot destructure property 'data' of '(intermediate value)' as it is undefined.
I followed this tutorial - enter link description here
Just modified it to what I wanted. This is my graphql:
query {
posts {
data {
attributes {
heading
}
}
}
}
And this is my vs code:
export async function getStaticProps() {
const client = new ApolloClient({
url: 'http://localhost:1337/graphql/',
cache: new InMemoryCache(),
})
const { data } = await client.query({
query: gql`
query {
posts {
data {
attributes {
heading
}
}
}
}
`,
})
return {
props: {
posts: data.posts,
},
}
}
FULL CODE:
import { ApolloClient, InMemoryCache, gql } from '#apollo/client'
export default function Blog({ posts }) {
console.log('posts', posts)
return (
<div>
{posts.map(post => {
return (
<div>
<p>{posts.heading}</p>
</div>
)
})}
</div>
)
}
export async function getStaticProps() {
const client = new ApolloClient({
url: 'http://localhost:1337/graphql/',
cache: new InMemoryCache(),
})
const { data } = await client.query({
query: gql`
query {
posts {
data {
attributes {
heading
}
}
}
}
`,
})
return {
props: {
posts: data.posts,
},
}
}
I really don't know where to begin with this.
Firstly check whether or not you are receiving empty data from API.
If its array, check its length or use methods like Array.isArray(myArray).
If its object, make a function like this to check objects.
function isObjectEmpty(obj) {
return (
!!obj && // 👈 null and undefined check
Object.keys(obj).length === 0 &&
obj.constructor === Object
)
}
export default isObjectEmpty
if the data is empty return notFound prop as true to show your 404 page.
// This function gets called at build time
export async function getStaticProps({ params, preview = false }) {
// fetch posts
// check validity data
return isObjectEmpty(pageData)
? { notFound: true }
: {
props: {
posts
}
}
}
Secondly add a failsafe mechanism like the use of optional-chaining to securely access nested values/properties.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
export default function Blog({ posts }) {
console.log('posts', posts)
return (
<div>
{posts?.length && posts?.map(post => {
return (
<div>
<p>{posts?.heading}</p>
</div>
)
})}
</div>
)
}
I was running into the same error while testing using Jest.
It turns out I was mocking all of graphql, but I had to specifically mock the return value.

why does my graphql return an empty array?

I am newbie with graphql. I have a front-end project (nextjs) and back-end(strapi).
This is my code
import { ApolloClient, InMemoryCache, gql } from '#apollo/client'
export default function Blog({ posts }) {
console.log('posts', posts)
return (
<div>
{posts.map(post => {
return (
<div>
<p>{posts.heading}</p>
</div>
)
})}
</div>
)
}
export async function getStaticProps() {
const client = new ApolloClient({
url: 'http://localhost:1337/graphql/',
cache: new InMemoryCache(),
})
const { data } = await client.query({
query: gql`
query {
posts {
data {
attributes {
heading
}
}
}
}
`,
})
return {
props: {
posts: data.posts,
},
}
}
alongside this, I also get this message "cannot destructure property of intermediate value". Does anybody know why, i'm sure the code is correct.
Firstly i recommend creating a folder in root and put all graphql codes and you have also a syntax error:
let me give you an example:
/index.js
import { ApolloClient, InMemoryCache, gql } from "#apollo/client";
const client = new ApolloClient({
uri: API,
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: "network-only",
},
},
});
//get category ids
const getCatIds = async () => {
try {
const { data } = await client.query({
query: gql`
query categoriesId {
categories(sort: "id:ASC") {
id
name
}
}
`,
});
return data.categories;
} catch {
console.log("error appolo");
}
};
export {getCatIds}

vue.js how to call multiple url data in single axios

i am trying get multiple url data in single axios. i already added single url but i want to add another url.
i tired this but it giving null object error
{{ BusinessCount }}
{{ UserCount }}
import axios from "axios";
export default {
data() {
return {
businesslists: [],
Userslist: [],
};
},
async asyncData({ $axios }) {
let { datas } = await $axios.$get("/Userslist");
return {
Userslist: datas,
};
},
computed: {
UserCount() {
return Object.keys(this.Userslist).length;
},
},
async asyncData({ $axios }) {
let { data } = await $axios.$get("/Businessregisterlist");
return {
businesslists: data,
};
},
computed: {
BusinessCount() {
return Object.keys(this.businesslists).length;
},
},
};
i want to show like this
<p>{{ BusinessCount }}</p>
<p>{{ UserCount }}</p>
1st url
/Businessregisterlist
2nd url
/Userlist
my code
<template>
<p>{{ BusinessCount }}</p>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
BusinessCounts: [],
};
},
async asyncData({ $axios }) {
let { datad } = await $axios.$get("/Businessregisterlist");
return {
BusinessCounts: datad,
};
},
computed: {
BusinessCount() {
return Object.keys(this.BusinessCounts).length;
},
},
};
</script>
In your tried code you define the asyncData function 2 times. That's incorrect. But you can make 2 calls to the server in a single asyncData function.
Try:
async asyncData({ $axios }) {
let { datad } = await $axios.$get("/Businessregisterlist");
let { dataUsers } = await $axios.$get("/Userslist");
return {
Businesslist: datad,
Userslist: dataUsers
};
},
computed: {
BusinessCount() {
return Object.keys(this.Businesslist).length;
},
UserCount() {
return Object.keys(this.Userslist).length;
},
},
Make sure you correctly define the Businesslist and Userslist in the data section.

How to properly pass input values to a function using the composition api in vue?

I have an input field that contains a postcode. On submit I want to pass the postcode as an object to an axios request. I have created a CodeSandbox here: https://codesandbox.io/s/determined-beaver-8ebqc
The relevant code is:
App.vue
<template>
<div id="app">
<input v-model="postcode" type="text" placeholder="Enter Postcode">
<button #click="getAddress">Submit</button>
</div>
</template>
<script>
import useAxios from "#/composition/use-axios";
export default {
name: "App",
setup() {
const { sentData, response, fetchData } = useAxios(
"api/address/lookup-address",
"postcode",
"Failed Finding Address"
);
return {
postcode: sentData,
address: response,
getAddress: fetchData
};
}
};
</script>
use-axios.js
import { reactive, toRefs } from "#vue/composition-api";
import axios from "axios";
export default function (url, objectData, errorMessage) {
const state = reactive({
sentData: null,
response: null
});
const fetchData = async () => {
console.log("Sent Data:", state.sentData);
console.log("Response:", state.response);
console.log("URL:", url);
console.log("Object Data:", objectData);
console.log("Object:", { [objectData]: state.sentData });
console.log("Error Message:", errorMessage);
const config = { headers: { "Content-Type": "application/json" } };
try {
const res = await axios.post(url, [objectData]: state.sentData, config);
state.response = await res.data;
} catch (error) {
// Error handling stuff
}
}
return { ...toRefs(state), fetchData };
}
Converting the postcode input string to an object in this way seems very hacky. Also, this would get very messy if I needed to send multiple parameters to the axios request. Say if I want to pass { id: "1234", user: "Me" }, I would like to be able to construct that like:
sentData = { id: ${id}, user: ${user} }
But I'm not able to do this. What is the proper way to do this so that I can keep use-axios generic?
You will need to import ref, reactive and computed from the composition-api and then use them like this:
<script>
import useAxios from "#/composition/use-axios";
import { ref, reactive, computed } from "#vue/composition-api";
export default {
name: "App",
setup() {
let object = ref("");
let state = reactive({ postcode: "" });
const sentDataObject = computed(() => {
state.postcode = object;
return state;
});
const addressList = useAxios(
"api/address/lookup-address",
sentDataObject.value,
"Failed Finding Address"
);
return {
addresses: addressList.response,
postcode: object,
getAddress: addressList.fetchData
};
}
};
</script>
change use-axios.js to:
import { reactive, toRefs } from "#vue/composition-api";
import axios from "axios";
export default function (url, objectData, errorMessage) {
const state = reactive({
sentData: null,
response: null
});
const fetchData = async () => {
console.log("Sent Data:", state.sentData);
console.log("Response:", state.response);
console.log("URL:", url);
console.log("Object Data:", objectData);
console.log("Error Message:", errorMessage);
const config = { headers: { "Content-Type":
"application/json" } };
try {
const res = await axios.post(url, objectData, config);
state.response = await res.data;
} catch (error) {
// Error handling stuff
}
};
return { ...toRefs(state), fetchData };
}
See Codesandbox demo here: https://codesandbox.io/s/dawn-glade-ewzb7

How to get ajax request in redux?

I'm stupid, I still can't get ajax request in redux. I don't understand, where should I get getState in action. In component, I using connect that link action and reducer. Then I using componentDidMount that call an action in a component. How to get ajax request in redux from server? Help me to understand this disorder. I tried to understand the examples of redux, but it's has no effect. If I start a server, get warning : getDefaultProps is only used on classic React.createClass definitions. Use a static property named defaultProps instead.
Action
import $ from 'jquery';
export const GET_BOOK_SUCCESS = 'GET_BOOK_SUCCESS';
export default function getBook() {
return (dispatch, getState) => {
$.ajax({
method: "GET",
url: "/api/data",
dataType: "application/json"
}).success(function(result){
return dispatch({type: GET_BOOK_SUCCESS, result});
});
};
}
Reducer
import {GET_BOOK_SUCCESS} from '../actions/books';
const booksReducer = (state = {}, action) => {
console.log(action.type)
switch (action.type) {
case GET_BOOK_SUCCESS:
return Object.assign({}, state, {
books: action.result.books,
authors: action.result.authors
});
default:
return state;
}
};
export default booksReducer;
component
function mapStateToProps(state) {
console.log(state)
return {
books: state.books,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({getBooks: () => getBook(),}, dispatch);
}
#Radium
#connect(mapStateToProps, mapDispatchToProps)
class booksPage extends Component {
static propTypes = {
getBooks: PropTypes.func.isRequired,
};
componentDidMount() {
const { getBooks } = this.props;
getBooks();
}
render() {
const {books} = this.props;
index.js
const store = configureStore({}, routes);
ReactDOM.render((
<div>
<Provider store={ store }>
<ReduxRouter />
</Provider>
<DebugPanel top right bottom>
<DevTools
store={ store }
monitor={ LogMonitor }
visibleOnLoad />
</DebugPanel>
</div>),
document.getElementById('root')
);
configureStore
function configureStore(initialState, routes) {
const store = compose(
applyMiddleware(
promiseMiddleware,
thunk,
logger
),
reduxReactRouter({ routes, history }),
devTools()
)(createStore)(rootReducer, initialState);
if (module.hot) {
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
export default configureStore

Resources