Axios Vue Js: How to get the value of this object to show in api get request url - axios

this is my vue file which accepts the id from table. this works I can get the data id from the table row
showProd (id) {
Products.showProd().then((response) => {
console.log(show1prod.product_name)
})
.catch((error) => {
alert(error)
})
this is my config file for calling the axios.get I can reach the backend but not generating the query because this url/api sends an object I believe not the id number
export default {
async showProd(id) {
return Api.get('/products/{id}',id)
},
loadProds () {
return Api.get('/products')
}
}

First make sure your API call is correct:
export default {
showProd(id) { // async not needed, axios returns promise
return axios.get('/products/' + id)
},
loadProds () {
return axios.get('/products')
}
}
You can than call these functions:
showProd (id) {
Products.showProd(id).then((response) => { // Note the id in the call
console.log(response.data.product_name) // Use the response object
})
.catch((error) => {
alert(error)
})

Related

How to use refetch method to send different queries using useQuery in react-query

I'm working with react-query in ReactJS to build a website.
I have the following code, where I fetch some data using useQuery():
const { error, data: movie, status, refetch } = useQuery({
queryKey: 'key1',
queryFn: async () => {
return await Promise.all([
axios.get(`API-1.com/get-some-data`), /*getting some data from api-1 */
axios.get(`API-2.com/get-some-data`), /*getting some data from api-2 */
]).then(([api1, ap2]) => {
return { data1: api1, data2: api2 }
})
}
})
The problem I'm facing is getting somtimes a 404 response from one of the apis, so I need to refetch the data just from the other api that doesn't cause the error.
I tried to use the refetch method inside onError, but it can't be used with parameters.
onError: (error) => {
refetch() /* refetch can't be used with parameters */
},
How can I handle this problem?
I ended up doing the following:
Writing the fetching part in an external function (so I can call the function with parameters)
Adding a try-catch block inside the queryFn to handle the errors
/********* this is the function where I fetch the data. *********/.
/********* with a param that tells me if i'll call API-2 or not *********/
const fetchData = async ({ isDataFoundInApi2 }) => {
return await Promise.all([
axios.get(`API-1.com/get-some-data`),
(!isDataFoundInApi2 && axios.get(`API-2.com/get-some-data`)),
]).then(([api1, api2]) => {
return { data1: api1, data2: api2 }
})
/********* the useQuery where the above method is called *********/
/********* first it sends true as a bool value, then if no *********/
/********* data was found in API-2, it sends false *********/
/********* from `catch` to prevent the fetching from API-2 *********/
const { error, data: movie, status } = useQuery({
queryKey: 'key1',
queryFn: async () => {
try {
return await fetchData({})
} catch (error) {
if (error.response?.status === 404)
return await fetchData({ isDataFoundInApi2: true }) // true means call only the first api
}
},
})

How can i make the interceptor run a function on error exept for one specific request?

this is my interceptor:
axios.interceptors.response.use(
(response) => {
if (error.response?.status === 403) {
unstable_batchedUpdates(() => {
// to force react state changes outside of React components
useSnackBarStore.getState().show({
message: `${i18n.t('forbidden')}: ${error.toJSON().config.url}`,
severity: 'error',
})
})
}
return Promise.reject(error)
}
)
I want this behavior all the time except when I make this specific call or at least except every head call
export const companiesQueries = {
headCompany: {
name: 'headCompany',
fn: async (companyId) => {
return await axios.head(`/companies/${companyId}`)
},
},
fixed by applying these changes to the api call:
const uninterceptedAxiosInstance = axios.create()
headCompany: {
name: 'headCompany',
fn: async (companyId) => {
return await
uninterceptedAxiosInstance.head(`/companies/${companyId}`)
},
}

Axios' then() call to external function cannot get data

methods: {
getHomeInfo() {
axios.get("/js/index.json").then(this.getHomeInfoSucc());
//err:undefined
axios.get("/js/index.json").then(function(res) {
console.log(res.data);
});
//Data available
},
getHomeInfoSucc(res) {
console.log(res);
}
}
I used Axios in Vue to use the anonymous function in Axios's then () to get data, but in then (), I call the function in methods to get the response data undefined
You need a callback:
methods: {
getHomeInfo() {
axios.get("/js/index.json").then((res) => this.getHomeInfoSucc(res));
//err:undefined
axios.get("/js/index.json").then(function(res) {
console.log(res.data);
});
//Data available
},
getHomeInfoSucc(res) {
console.log(res);
}
}

Wuxt.js (Nuxt.js) getting out data from axios response

I want to fetch out menu items from the Wordpress json response with Wuxt framework (Nuxt + Wordpress), but I can't access the data object outside the fetch (error message is that data is not defined)
This is my code
<script>
import axios from 'axios'
import Logo from '~/components/Logo'
export default {
components: {
Logo
},
async fetch ({ params, error }) {
try {
let { data } = await axios.get('http://localhost:3080/wp-json/wuxt/v1/menu')
return data
} catch (e) {
error({ message: 'Not found', statusCode: 404 })
}
}
}
</script>
How can the data object be accessed, for inserting into the template?
If you are using fetch than all your data should be commiting into store, and accessed from it. If you want to return data, use asyncData method.
I had to change the code a bit, that it returns a data function with variable, so it looks like this.
export default {
components: {
Logo
},
data() {
return { menus: [] }
},
mounted() {
fetch('http://localhost:3080/wp-json/wuxt/v1/menu')
.then(response => {
response.json().then(menus => {
this.menus = menus;
})
})
}
}

Implementing redirect in Redux middleware

Let's say I have following action:
export function signIn(data) {
return {
type: USER_SIGN_IN,
promise: api.post('/sign_in', data)
}
}
and following middleware:
export default function promiseMiddleware() {
return next => action => {
const { promise, type, ...rest } = action
if (!promise) {
return next(action)
}
const SUCCESS = `${type}_SUCCESS`
const REQUEST = `${type}_REQUEST`
const ERROR = `${type}_ERROR`
next({ type: REQUEST, ...rest })
return promise
.then(res => {
next({ response: res.data, type: SUCCESS, ...rest })
return true
})
.catch(error => {
...
})
}
}
This code is loosely based on https://github.com/reactGo/reactGo/
But what if in then callback after calling next I want to make a redirect to another path?
I did following. I passed redirect url through action:
export function signIn(data) {
return {
type: USER_SIGN_IN,
promise: api.post('/sign_in', data),
redirect: '/'
}
}
and added another call of next method with push from react-router-redux.
import { push } from 'react-router-redux'
export default function promiseMiddleware() {
return next => action => {
const { promise, type, redirect, ...rest } = action
...
return promise
.then(res => {
next({ response: res.data, type: SUCCESS, ...rest })
next(push(redirect))
return true
})
.catch(error => {
...
})
}
}
It seems like it works, but I'm not sure if this is a good idea or if there are some pitfalls of multiple next calls and I shouldn't do like this?
Maybe there are some better approaches for implementing such redirects?