I do a get in the api and I can collect their data but when I assign it to a data variable it doesn't get it
data() {
return {
departamento: [],
}
},
setup() {
onMounted(() => {
const token = setToken.getToken();
axios
.get("https://sig-fpto.herokuapp.com/api/departamentos/buscarTodos", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
console.log(response.data);
this.departamento = response.data
})
.catch((err) => console.log(err.response));
})
You are mixing Vue2 syntax with Vue3. Here is what should work:
setup() {
const departamento = ref([]);
onMounted(() => {
const token = setToken.getToken();
axios
.get("https://sig-fpto.herokuapp.com/api/departamentos/buscarTodos", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
console.log(response.data);
departamento.value = [...response.data];
})
.catch((err) => console.log(err.response));
})
return {
departamento,
}
}
Related
In my app I'm sending a request to my backend app from which I get a response with id like { 'id': '12345'}. I saves this id as loadId inside data, here:
export default {
name: 'SyncProducts',
data() {
return {
loadId: '',
Now I want to send another POST fetchSyncedProductsResultRequest when this data loadId change from empty. How to do so?
Below my code:
imports.js
const createApparelMagicProductsRequest = (self, products) => {
const jwtToken = self.$store.state.idToken;
console.log(products)
console.log()
const payload = JSON.stringify({ product_codes: products['product_codes'].split(',') })
return axios
.post(`/api/v1/imports/products_batches`, payload,{
headers: {
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.data['id'])
};
const fetchSyncedProductsResultRequest = (token, id) => {
return axios
.get(`/api/v1/imports/products_batches`, {
params: { id: id },
headers: {
Authorization: `Bearer ${token}`,
}
})
.then(response => {
return response.data['result']
})
};
sync_products.vue
<script>
import {
fetchSyncedProductsResultRequest,
createApparelMagicProductsRequest
} from '../../api/imports'
export default {
name: 'SyncProducts',
data() {
return {
styleCodes: [],
fetchedProductSyncResult: [],
loadId: '',
}
},
async mounted() {
await fetchSyncedProductsResultRequest(this, load.id)
this.syncedProductsFetched = true
this.pageChanged(this.currentPage)
},
async mounted() {
const jwtToken = this.$store.state.idToken;
fetchSyncedProductsResultRequest(jwtToken).then(data => {
this.fetchedProductSyncResult = data
})
},
</script>
Use a watcher on loadId that calls fetchSyncedProductsResultRequest() with the new value if it's changed from an empty string to a non-empty string:
export default {
watch: {
loadId(newValue, oldValue) {
if (!oldValue && newValue) {
const jwtToken = this.$store.state.idToken;
fetchSyncedProductsResultRequest(jwtToken, newValue).then(data => {
this.fetchedProductSyncResult = data
});
}
}
}
}
demo
I tried to use this metaweather API but it's not working. this is a react project and I'm tyring on localhost. plz, can anyone show me what am I doing wrong here?
const fetchWeatherData = async() =>{
fetch('https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02', {
method:'GET',
mode:'no-cors',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
console.log('response',response);
return response.json();
})
.then(data => {
console.log('data',data);
})
.catch((err) => {
console.log(err)
})}
these are logs i got
You just didn't close the function with curly brackets, I have tested it and it works fine , just call the function fetchWeatherData
const fetchWeatherData = async() => {
fetch('https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02', {
method:'GET',
mode:'no-cors',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
return response.json();
})
.then(data => {
console.log('data',data);
})
.catch((err) => {
console.log(err)
})
}
fetchWeatherData()
whenever I click the delete button its works fine but I don't get the output like " deleted successfully " its shows .then undefined..
const deleteThisCategory = (CategoryId) => {
deleteCategory(CategoryId, user._id, token).then(data => {
if (data.error) {
console.log(data.error);
} else {
preload();
}
});
};
here is the delete category API call
export const deleteCategory = (userId, categoryId , token) => {
fetch(`${API}/category/${categoryId}/${userId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
},
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
It should be like this. deleteCategory needs to send only promise. Later where ever you are resolving you have to use then.
export const deleteCategory = (userId, categoryId , token) => {
return fetch(`${API}/category/${categoryId}/${userId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
}
})
};
const deleteThisCategory = (CategoryId) => {
deleteCategory(CategoryId, user._id, token).then(data => {
preload();
}).catch(err => {
console.log(err);
})
};
const getCustomers = async (token) => {
try {
const response = await axios.get(`${base_url}/customers`, { headers: { 'Authorization': `Bearer ${token}`} })
return response.data
} catch(error) {
logger.error(error)
}
i'm using axios to make a request to an api, and i keep getting the same error.
error: undefined {"config":{"url":"https://api.contaazul.com/v1/customers","method":"get","headers":{"Accept":"application/json","Authorization":"Bearer EU5KBm8ft1ZB4vFy9I89xYQWnzqcbULS","User-Agent":"axios"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"code":"HPE_INVALID_HEADER_TOKEN"}
already tried deleting node_modules and using other versions of node
Try this
const getCustomers = async (token) => {
await axios.get(`${base_url}/customers`, {
headers: {
"Authorization": `Bearer ` + token
}
})
.then(response => {
return response.data;
})
.catch(err => {
console.log(err)
});
}
How can I update only one data through API? I want to change from status: 4 to status: 5
Here's my code
export const cancelRequest = async id => {
const response = await fetch(`API_URL/link/link/${id}`, {
method: 'put',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${Auth.getToken()}`,
},
});
return getData(response);
};
Calling it through another file
const onCancelRequest = async id => {
let cancelItem = dataAll.filter(item => item.id == id);
await TriggerRequestAPI.cancelRequest(id)
.then(data => {
data.json();
cancelItem[0].status = 5;
setIsAll(cancelItem);
})
.catch(error => console.log(error));
};
You need to update your item first then call the API:
const onCancelRequest = async id => {
const cancelItems = dataAll.filter(item => item.id == id);
if(cancelItems.length === 0) {
return;
}
// Update the item
cancelItems[0].status = 5;
// Then call the API
await TriggerRequestAPI.cancelRequest(id, cancelItems[0])
.then(data => {
return data.json();
})
.then(item => {
setIsAll(cancelItems);
})
.catch(error => console.log(error));
};
API:
export const cancelRequest = async(id, item) => {
const response = await fetch(`API_URL/link/link/${id}`, {
method: 'put',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${Auth.getToken()}`,
},
body: JSON.stringify(item) // item to update
});
return getData(response);
};