How to split axios functions and components in vue3? - javascript

I think it is better to split the axios commands and the vue components.
This is my directory structure:
src
api
- products.js
components
- Products.vue
products.js
import axios from 'axios';
const listProducts = () => {
const headers = { "Content-Type": "application/json" };
let url = "http://localhost:8001/api/v1/products";
const response = axios.get(url, headers);
return response.data
}
export default {
listProducts,
}
Products.vue:
<template>
<div>{{ products }}</div>
</template>
<script>
import { listProducts } from "#/api/products.js"
export default {
data () {
return {
products: {},
}
},
created() {
this.getProducts();
},
methods: {
getProducts() {
this.products = listProducts();
}
}
}
</script>
But this.products is undefined. I tried some stuff with async and await, but nothing works.
And what would be best practice in vue3?

axios.get() returns a Promise, so response in the following line is actually a Promise (not the Axios response itself):
const listProducts = () => {
⋮
const response = axios.get(url, headers);
return response.data // ❌ `response` is a `Promise`
}
To get the response, you can await the result of the axios.get() call:
👇
const listProducts = async () => {
⋮ 👇
const response = await axios.get(url, headers);
return response.data
}
Similarly, this updated listProducts() function now returns a Promise because it's async. Your component now must await the result of listProducts():
// Products.vue
export default {
⋮
methods: {
👇
async getProducts() {
👇
this.products = await listProducts();
}
}
}
demo

Related

What if axios call in getServerSideProps() failed? How to repeat

I'm trying to pre render page using getServerSideProps in Next.js and everything works perfectly.
But what if the axios call failed due to server issue or Network error?
How can I repeat the call?
Here's my code:
export async function getServerSideProps() {
let ImagesList = {};
await axios
.get("https://www.*****.com/api/home")
.then((response) => {
if (response.data) {
ImagesList = response.data
}
})
.catch((err) => { });
return {
props: {
ImagesList,
}
}
}
you can try to wrap your axios call inside a while loop,
let result = false;
while(!result) {
await axios
.get("https://www.*****.com/api/home")
.then((response) => {
result = true
if (response.data) {
ImagesList = response.data
}
})
.catch((err) => { });
}

useQuery doesn't return the data and the function is returned

I'm trying to get the list of the chats in my app using react-query(useQuery). my API call is in a different component and I'm using Axios to get the data. but the component is returning the function itself not the data .which part is Wrong?
import { useQuery } from "react-query";
import axios from "axios";
const getContacts = async () => {
const headers = { Authorization: localStorage.getItem("token") };
const options = {
method: "GET",
url: "http://127.0.0.1:8000/chat/mine/",
headers: headers,
};
const { data } = await axios.request(options);
return data;
};
function GetUserDataUseQuery() {
return useQuery("getContacts", getContacts);
}
export default GetUserDataUseQuery;
function getUserData() {
const data = GetUserDataUseQuery;
return (dispatch) => {
dispatch({
type: GET_CONTACTS,
payload: [],
});
};
}
I suggest you refactor your code a little to fix some of your problems:
const getContacts = async () => { /*...*/ }
const useGetContacts = () => {
return useQuery('getContacts', getContacts)
}
// `useGetContacts` is a hook, so it should be called inside of a
// component or another hook - you *cannot* call a hook inside of a
// simple function, which is what you're attempting to do inside `getUserData`
function MyComponent() {
const contacts = useGetContacts();
// ...
}
Alternatively, if you do want to use getContacts as if it was a function, then simply don't wrap it inside a useQuery, since that's what turns it into a hook.
async function getUserData() {
const data = await getContacts()
// ...
}

use axios in getStaticProps in next js

i have a next project.in this project i used axios for send and recieved request data.
but i have a problem when i use axios in getStaticProps function i get an error in my index.js page
this is my index.js
import axios from "axios";
const Home = (props) => {
console.log(props);
return <div>d</div>;
};
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
return {
props: {
data: res
}
};
}
export default Home;
and this is my index.js page in my browser
I would be very grateful if anyone could help me
it worked
try {
const result = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
const data = result.data;
return {
props: {
data: data
}
}
} catch (error) {
console.log(error);
}
You should use res.data. Next time, I recommend to use console.log(res) and see the object that you receive
Add JSON.stringify when calling an asynchronous function that returns an object.
Try modifying the getStaticProps function like this:
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
const stringRes = JSON.stringify(res);
return {
props: {
data: stringRes
}
};
}
OR
Use .text() to convert the response data to text like this:
export async function getStaticProps() {
const res = await axios.get('https://jsonplaceholder.typicode.com/todos/1').lean();
const textRes = await res.text();
return {
props: {
data: textRes
}
};
}

Return Data from Axios

I am trying to return the response from an axios API call. I don't quite get what a promise is and all the tutorials/information I find they only log the response, I want to return it.
Here is what I have, but when I call getPokemon it's undefined.
const axios = require('axios');
const getPokemon = () => {
axios.get('https://pokeapi.co/api/v2/pokemon/')
.then(function (response) {
console.log("Response:", response.data.results);
return response.data.results;
})
.catch(function (error) {
return null;
});
}
export {getPokemon};
If this is a React app then you want to do your Axios call in componentDidMount. Axios automatically returns a promise.
class Example extends Component {
constructor(props) {
super(props);
this.state = {
data: ""
};
}
componentDidMount() {
axios
.get("https://pokeapi.co/api/v2/pokemon/")
.then(res => {
console.log(res);
this.setState({
data: res.data.results
});
})
.catch(err => {
console.log(err);
});
}
render() {
let pokemon = this.state.data;
let display = Object.values(pokemon).map((item, key) => {
return (
<div>
<p>{item.name}</p>
<p>{item.url}</p>
</div>
);
});
return (
<div>{display}</div>
);
}
}
export default Example;
Doing it like this will send the Axios request after the React app has loaded and set the JSON data in the component state. You should be able to access the JSON data via this.state.data.
Check out this Codepen example with working API call.
Well, first of all, I suggest you read about promises.
a good method for achieving what you need is by using async/await syntax check out the following code:
const axios = require('axios');
const getPokemon = async () => {
try{
let res = await axios.get('https://pokeapi.co/api/v2/pokemon/');
return res.data.results;
}
catch(error){
return null //that's what you did in your code.
}
}
export {getPokemon};
Remove ".result"
const axios = require("axios");
const getPokemon = async () => {
try {
let res = await axios.get("https://jsonplaceholder.typicode.com/users");
return res.data; **here remove his .result**
} catch (error) {
return null; //that's what you did in your code.
}
};
export default getPokemon;
In index.js or any page call it:
import getPokemon from "./GetPokimon";
const xyz = async () => {
const data = await getPokemon();
alert(JSON.stringify(data));//u will see the data here
}
xyz(); //calling getPokemon()

Why can't I load the API?

I'm going to call the movie API using the redux in the react application.
During the process of calling the movie API using the redux-thunk,
An error occurs while calling the callAPI function on the lib/THMb path.
//movie_project/src/lib/THMb.js
import axios from 'axios';
const key = "xxxxxxx";
const url = `https://api.themoviedb.org/3/movie/now_playing?api_key=${key}&language=ko&page=1&region=KR`;
export const callAPI = async () =>{
await axios.get(`${url}`);
}
import { handleActions } from "redux-actions";
import axios from "axios";
import * as movieAPI from '../lib/THMb';
// action types
const GET_MOVIES = 'movie/GET_MOVIES';
const GET_MOVIES_SUCCESS = 'movie/GET_MOVIES_SUCCESS';
const GET_MOVIES_FAILURE = 'movie/GET_MOVIES_FAILURE';
export const getMovies = () => async dispatch => {
dispatch({ type: GET_MOVIES });
try{
const res = await movieAPI.callAPI(); // failed
dispatch({
type: GET_MOVIES_SUCCESS, // 요청 성공
payload: res.data.results, // API 요청 결과 값
})
}catch(e){
dispatch({
type: GET_MOVIES_FAILURE, // 요청 실패
payload: e,
error: true
})
throw e;
}
}
const initialState ={
movieList : [],
error: null
}
const movie = handleActions(
{
[GET_MOVIES]: state => ({
...state,
// loading..
}),
[GET_MOVIES_SUCCESS]: (state, action) => ({
...state,
movieList: action.payload,
}),
[GET_MOVIES_FAILURE]: (state, action) => ({
...state,
// loading...
})
},
initialState
)
export default movie;
enter image description here
However, no error occurs when calling url from within the getMovies function.
export const getMovies = () => async dispatch => {
dispatch({ type: GET_MOVIES }); // 요청의 시작을 알림.
try{
//const res = await movieAPI.callAPI(); // failed
// success
const res = await axios.get(`https://api.themoviedb.org/3/movie/now_playing?api_key=xxxxx&language=ko&page=1&region=KR`);
dispatch({
type: GET_MOVIES_SUCCESS, // 요청 성공
payload: res.data.results, // API 요청 결과 값
})
Why do errors occur in the first case???
That's because in the first case you are not returning anything. You should try this:
export const callAPI = async () => {
let res = await axios.get(`${url}`);
return res;
}
Hope this works for you.
the error occurs in callAPI function, not in getMovies because in payload you are assuming res variable to fetch the data from it and you successfully get it in getMovies function but not in callAPI.
because you did not return anything from callAPI method that's why res variable is null and it throws the error.
just replace you callAPI function with the below code.
export const callAPI = async () =>{
const res await axios.get(`${url}`);
return res
}
hopefully, it will work just give it a try

Categories

Resources