API Fetch update only one data - javascript

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);
};

Related

How can I refresh data in user variable

How To Refresh User data coming from a variable route? I have a variable called "user" which is coming from a different screen by "react navigation" route that user variable contains all the data I need, So How can I reload that user variable data after "Set follow" is true without fetching anything because "user" variable data is coming is fetching from a different screen?
Code:
const Profile = ({ navigation, route }) => {
const { user } = route.params; // HERE IS THAT USER VAR
const [issameuser, setIssameuser] = useState(false)
const [follow, SetFollow] = useState(false)
const isMyProfile = async (otherprofile) => {
AsyncStorage.getItem('user').then((loggeduser) => {
const loggeduserobj = JSON.parse(loggeduser)
if (loggeduserobj.user.username == otherprofile[0].username) {
setIssameuser(true)
}
else {
setIssameuser(false)
}
})
}
const CheckFollow = async (otherprofile) => {
AsyncStorage.getItem('user')
.then(loggeduser => {
const loggeduserobj = JSON.parse(loggeduser);
return fetch('http://10.0.2.2:3000/checkfollow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
followfrom: loggeduserobj.user.username, followto: otherprofile[0].username
})
})
})
.then(res => res.json())
.then(data => {
if (data.message == "User in following list") {
SetFollow(true)
} else if (data.message == "User not in following list") {
SetFollow(false)
} else {
alert('Please Try Again!')
}
})
}
const FollowUser = async (otherprofile) => {
const loggeduser = await AsyncStorage.getItem('user')
const loggeduserobj = JSON.parse(loggeduser)
fetch('http://10.0.2.2:3000/Follow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
followfrom: loggeduserobj.user.username, followto: otherprofile[0].username
})
})
.then(res => res.json())
.then(data => {
if (data.message == "User Followed") {
SetFollow(true) // HERE I WANT TO RE-LOAD USER VAR DATA
}
else {
alert("Pleas Try Again")
}
})
}
useEffect(() => {
isMyProfile(user)
CheckFollow(user)
},)
}
is their any method to do that or i need to use socketio?

Data variable dont get the response in vuejs 3

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,
}
}

Passing argument to async / await function returns "undefined"

When posting data to an API and get a response, if I hardcode the body data inside the fetch call (body: "XYZ12345") it works fine, this is an example:
const vatValidationRequest =
fetch(
'/api/vies/validateVAT.php', {
method: 'POST',
body: "XYZ12345",
headers: {
'Content-Type': 'application/text'
}
})
.then((response) => response.text())
.then((responseText) => {
return responseText;
});
const validateVAT = async () => {
const viesResponse = await vatValidationRequest;
console.log(viesResponse);
};
validateVAT();
However, if I try to pass the body data as an argument (body: vatNumber), the validateVAT() function returns "undefined". This is what's not working:
const vatValidationRequest = (vatNumber) => {
fetch(
'/api/vies/validateVAT.php', {
method: 'POST',
body: vatNumber,
headers: {
'Content-Type': 'application/text'
}
})
.then((response) => response.text())
.then((responseText) => {
return responseText;
});
}
const validateVAT = async (vatNumber) => {
const viesResponse = await vatValidationRequest(vatNumber);
console.log(viesResponse);
};
validateVAT("XYZ12345");
Any clues about how to pass the argument to the async function? thanks!
The problem is that you are not returning the response from the method. You should do this:
const vatValidationRequest = (vatNumber) => {
return fetch(
'/api/vies/validateVAT.php', {
method: 'POST',
body: vatNumber,
headers: {
'Content-Type': 'application/text'
}
})
.then((response) => response.text())
.then((responseText) => {
return responseText;
});
}
const validateVAT = async (vatNumber) => {
const viesResponse = await vatValidationRequest(vatNumber);
console.log(viesResponse);
};
validateVAT("XYZ12345");

Pass query parameters to Snipcart API url inside a Netlify function

I’m trying to get JSON product data from Snipcart by querying my Netlify function as below:
const fetch = require("isomorphic-fetch");
const {SNIPCART_PRIVATE_KEY} = process.env;
const API_ENDPOINT = "https://app.snipcart.com/api/products";
const {snipcartID} = event.queryStringParameters;
const callAPI = async (event, context) => {
const auth =
'Basic ' +
Buffer.from(SNIPCART_PRIVATE_KEY + ':' + '').toString('base64');
const t = await fetch(API_ENDPOINT + "?userDefinedId=" + ${snipcartID || 'ABC'}, {
headers: {
Authorization: auth,
Accept: "application/json",
},
})
.then((response) => response.json())
.then(data => {
var results;
if (data) {
const {items} = data;
if (items) {
return {
name: items[0].name,
sales: items[0].statistics.numberOfSales,
};
}
}
return results;
})
.catch((error) => ({ statusCode: 422, body: String(error) }));
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers':
'Origin, X-Requested-With, Content-Type, Accept',
},
body: JSON.stringify(t),
};
};
exports.handler = callAPI;
I get the correct JSON data when I hard-code SNIPCART_ID in the function above. But I can’t pass my Snipcart id as a parameter using my page’s JavaScript as follows:
<script>
document.addEventListener("click", function (event) {
if (!event.target.matches("#collapsible")) return;
let URL = "/.netlify/functions/snipcart-getsales";
fetch(URL, "ABC")
.then((response) => response.json())
.then((data) => renderSales(data))
.catch(() => renderError());
});
function renderSales(data) {
const name = document.getElementById("name");
const sales = document.getElementById("sales");
const error = document.getElementById("error");
error.innerHTML = "";
name.innerHTML = data.name;
sales.innerHTML = data.sales;
}
function renderError() {
const error = document.getElementById("error");
error.innerHTML = "Whoops, something went wrong. Please try again later!";
}
</script>
What am I doing wrong here?
Can you console.log(event) before sending the request, to check if your function got the correct SNIPCART_ID that is send to the request.
I figured it out after some fiddling around :)
const fetch = require("isomorphic-fetch");
const {SNIPCART_PRIVATE_KEY} = process.env;
const API_ENDPOINT = "https://app.snipcart.com/api/products";
const callAPI = async (event, context) => {
const auth =
'Basic ' +
Buffer.from(SNIPCART_PRIVATE_KEY + ':' + '').toString('base64');
const querystring = event.queryStringParameters;
const userDefinedId = querystring.userDefinedId || 'ABC';
const t = await fetch(API_ENDPOINT + "?userDefinedId=" + userDefinedId, {
headers: {
Authorization: auth,
Accept: "application/json",
},
})
.then((response) => response.json())
.then(data => {
var results;
if (data) {
const {items} = data;
if (items) {
return {
name: items[0].name,
sales: items[0].statistics.numberOfSales,
};
}
}
return results;
})
.catch((error) => ({ statusCode: 422, body: String(error) }));
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers':
'Origin, X-Requested-With, Content-Type, Accept',
},
body: JSON.stringify(t),
};
};
exports.handler = callAPI;

the code is doing its work but I'm not getting the desired output

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);
})
};

Categories

Resources