Problem with the post format ( array) ReactJs - javascript

I would like to explain my problem of the day.
in the following code I map a table, and I post all of this in a database
everything works fine. the only problem and the format in which I receive it.
{
"id": 136,
"items": "[{\"title\":\"Campus (Pinte)\",\"quantity\":2}]",
}
I would rather recover it in another format than in arrays. here is my code:
postbackend = () => {
const newItems = this.props.items.map(item => {
const { title, quantity } = item;
return {
title,
quantity
};
});
const config = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ ...this.state, items: newItems })
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
this.props.history.replace("/OrderSummaryPaymentFalseScreen"); // Your Error Page
} else {
alert(`film ajouté avec l'ID ${res}!`);
this.props.history.push("/OderSummaryScreen"); // Your Success Page
}
})
.catch(e => {
console.error(e);
this.props.history.replace("/OrderSummaryPaymentFalseScreen"); // Your Error Page
})
.finally(() =>
this.setState({
redirect: true
})
);
};
Do you have an idea of how to fix this?

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?

How to update data at the same time after an ajax post request

I am doing a ajax post request to
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(samepleData)
})
.then(response => {
return response.json();
})
and after the product has been added to the cart, I open a drawer to show all items in the cart using a GET request to the endpoint
fetch(window.Shopify.routes.root + 'cart.js')
.then(response => response.json())
.then((cartData) => {
console.log(cartData);
if(cartData) {
showCartDrawer(quick_shop_desktop_container, cartData);
}
}).catch((err) => {
console.log(err);
})
and everything is working, it is loading and fetching data, but now once I am in the cart drawer, I have an option to increase quantity and decrease quantity, so everytime someone clicks on increase quanity, it should again make a post request to the first endpoint, and the product will be updated, but the new info will not gonna be shown at the same moment, How to update all the data after the product quantity is increased without refreshing the page and at the same moment? I haven't woked with this type of conditions before, any guide please?
EXAMPLE CODE:-
let samepleData = {
'items': [{
'id': myid,
'quantity': quantityValue
}]
};
btn.addEventListener('click', () => {
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(samepleData)
})
.then(response => {
return response.json();
}).then((data) => {
console.log(data);
if (data) {
fetch(window.Shopify.routes.root + 'cart.js')
.then(response => response.json())
.then((cartData) => {
console.log(cartData);
if(cartData) {
showCartDrawer(quick_shop_desktop_container, cartData);
}
}).catch((err) => {
console.log(err);
})
}
).catch((err) => {
console.log(err);
})
}
else {
addToCartBtn.innerHTML = `<span>Fail</span>`
}
})
})
And now inside the showCartDrawer
test.innerHTML = cartData.items.map(cartItem =>
`<div class="selliy-cart-item">
<h2>${cartItem.price}</h2>
</div>`
).join('');
increasequantityfromdrawer.addEventListener('click', () => {
let newdata = {
'items': [{
'id': myid,
'quantity': newvalue
}]
};
fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newdata )
})
.then(response => {
return response.json();
})
});

Getting data from metaweather API to react page

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()

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

how to fetch data with a condition using javascipt in react?

I want to load only specific number of rows where the condition satisfies.
However the following code fetches all the 25 rows and condition is not working.
Please someone help.
loadCommentsFromServer = () => {
fetch('/api/comments/', {
method: 'GET',
author: 'Dani'
})
.then(data => data.json())
.then((res) => {
if (!res.success) this.setState({ error: res.error });
else this.setState({ data: res.data });
});
}
I am very new to javascript and reactjs, any help will save my weekend.
You don’t have access to the response in your second callback there.
loadCommentsFromServer = () => {
return fetch('/api/comments/', {
method: 'GET',
author: 'Dani'
})
.then((res) => {
if (!res.success) this.setState({ error: res.error });
else res.json().then(data => this.setState({ data }));
});
}

Categories

Resources