How to update state with react js with componentDidUpdate and setState? - javascript

How to update the data with react js eg a user writes a comment how to make this messages show up to all other users?
I used setState in componentDidUpdate with a stop condition but it doesn't work.
If i don't make a condition, it work correctely but with infinite loop.
componentDidUpdate(prevProps, prevState) {
console.log("1" + prevState.changeRepComm.toString())
console.log("2" + this.state.changeRepComm.toString())
if (prevState.changeRepComm !== this.state.changeRepComm ) {
if (this.updateTimer) return;
this.updateTimer = setTimeout(() => {
//lister response comments
fetch('/api/ReponseCommentaire/listerReponseCommentaire', {
method: "GET",
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(response => {
console.log('Ajouter response:' + JSON.stringify(response))
this.setState({ ...this.state, reponseCommentaires: response });
})
.catch((err) => {
console.log('fetch failed => ', err);
})
}, 1000);
} }

If your looking to update every second, you can initialize a timer when component mounts.
componentDidMount(prevProps, prevState) {
if (this.updateTimer) { return; }
this.updateTimer = setInterval(() => {
fetch('/api/ReponseCommentaire/listerReponseCommentaire', {
method: "GET",
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(response => {
this.setState({
...this.state,
reponseCommentaires: response,
});
})
.catch((err) => console.log('fetch failed => ', err) )
}, 1000);
}

Related

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

undefined-is-not-an-object-evaluating-this-state-datasource.map

componentDidMount(){
fetch('https://boboboi.online/c_api_sales/get_dest',{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
port_code: 'CP-002',
api_key: 'ae9a6ce9a7479038d998060ef6d65ca9f86a13ed962a5366b3b0662cc52dde1b',
token: 'a959190d43520f8017ed2ca09ffc61bb'
}),
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
GetPickerSelectedItemValue=()=>{
Alert.alert(this.state.PickerValueHolder);
}
map() method can be used with array and not with object. So if you want to use map method you can try using it like Object.keys(this.state.dataSource).map((key, index)=> { //your function and logic });

Using setState in fetch. Error: Warning: Can't call setState (or forceUpdate) on an unmounted component

Complete Error Here
fetch('http://localhost:3000/signin', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.emailInput,
password: this.state.passwordInput,
}),
})
.then(response => response.json())
.then((data) => {
if (data === 'Success!') {
this.setState({ route: '/' }, () => {
document.getElementById('sign-in-button').click();
signIn();
});
}
});
I'm 90% sure that the error occurs because I'm setState-ing when fetching from the server.
I'm using the 'route' state to dynamically set up my NavLink from React Router v4.
If your function in render method, it will give that error. Move your fetch function a lifecycle method.
componentDidMount(){
fetch('http://localhost:3000/signin', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: this.state.emailInput,
password: this.state.passwordInput,
}),
})
.then(response => response.json())
.then((data) => {
if (data === 'Success!') {
this.setState({ route: '/' }, () => {
document.getElementById('sign-in-button').click();
signIn();
});
}
});
}

fetch data error with react native

I used two classes
I call the second class as below
let s = new SearchExtend();
output = s.fetchData(search)
alert(output)
The second function:
fetchData = (search) => {
fetch('http://example.com/search.php' , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
// Getting the search.
search: search
})
}).then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
But i get in "alert" undefined
When I use this.setState instead of return, I get the following error:
warning setstate(...) can only update a mounted or mounting component
You are getting undefined because you are using promises. Initially it returns undefined and once promise is resolved you get the actually data.
A better way to handle this would be to return the promise and resolve it externally as follows:-
const fetchApi = () => {
return fetch("https://swapi.co/api/people" , {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => {
return response.json();
})
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(JSON.stringify(error));
});
}
fetchApi()
.then((data) => {
console.log("data", data);
})

ReactJS several fetch requests with promise

I need several fetch requests in my application to fetch data from different collections. Therefore, I wanted to use promises to make it work.
I have never used promises and despite my research on stackoverflow and other websites, I was not able to make it work.
Essentially, I need two fetch requests and I want to save the result of these requests to 2 different states.
This is what I have as of right now:
getFormData () {
fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getIcons () {
fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getData () {
return Promise.all([this.getFormData(), this.getIcons()])
}
componentDidMount () {
this.getData()
.then(([formdata, icons]) => {
console.log(form + " " + icons);
})
.catch(err => console.log('There was an error:' + err))
}
But this did not work.
I also tried putting the promise in my componentDidMount() lifecycle method, like so:
componentDidMount () {
return Promise.all([this.getFormData(), this.getIcons()])
.then(([formdata, icons]) => {
console.log(formdata + " " + icons);
})
.catch(err => console.log('There was an error:' + err))
}
But this didn't work eiter.
I would like to save the data from /formdata to a state with the same name and the same goes for icons, but in the console it simply returns undefined undefined, instead of the formdata and the icons.
Where am I making a mistake in my code? How would I fix it?
You need to return Promise object from your methods. As of now you are not returning anything, so it's implicit undefined.
Try this:
getFormData () {
return fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getIcons () {
return fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
Just adding to #dfsq's answer, after returning the promises you can update the state within each function:
constructor(props) {
super(props);
this.state = {
formData = {},
icons: {}
}
}
getFormData () {
return fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json(
this.setState({ formData: res.json })
))
}
getIcons () {
return fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json(
this.setState({ icons: res.json })
))
}

Categories

Resources