Does anyone know how to use data that was calculated in one script in another script?
For example within head this script gets a customer email
Edit: Added var customer_email; but getting undefined when using customer_email outside of loadSuccess() function.
<script>
var customer_email;
async function loadSuccess() {
const response = await fetch('/.netlify/functions/success', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then((res) => res.json())
.catch((err) => console.error(err));;
customer_email = response.session.customer_details.email;
console.log(customer_email);
}
loadSuccess();
console.log(customer_email);
}
</script>
<script>
console.log(customer_email);
</script>
Now in a different also within , how can customer_email be used?
In this example, only the 1st console.log(customer_email) within loadSuccess() prints the email. The other 2 print undefined.
Make customer_email a global variable
<script>
var customer_email;
async function loadSuccess() {
const response = await fetch('/.netlify/functions/success', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then((res) => res.json())
.catch((err) => console.error(err));;
customer_email = response.session.customer_details.email;
}
loadSuccess();
}
</script>
You are able to assign your value to a global variable, such as window._customer_Email.
window._customer_Email = response.session.customer_details.email;
Then you can access this in the same way
console.log(window._customer_Email)
Note that global variables are something recommended against because they cannot be garbage collected easily and also pollute the global state (risking conflicts)
Related
Im using mockapi for a very simple project. In order to change data, i have to send PUT request. I can send the request using PostMan like in the pictures below. And everything works perfect. But i don't know where to add path variables in fetch api using Javascript. I know how to add body and i know how to add headers but i cannot figure out where to add path variables.
My code is:
async function getData() {
let url = "https://blablabla/moves/:id";
const fetchData = {
method: "PUT",
body: {
roomid: 2512,
move: "move 2",
id: 2,
},
headers: new Headers({
"Content-Type": "application/json; charset=UTF-8",
}),
};
await fetch(url, fetchData)
.then((response) => response.json())
.then((data) => console.log(data));
}
And the Postman Screenshot:
Postman Screenshot
I added the key: id part. All i want to know is that how can i add the "value: 2" part (that you can see in the picture) to fetch api. Any help will be appreciated.
I tried to fetch PUT request in javascript but couldn't figure out where to put Path Variables.
There are no path variables in the fetch api, but you can pass the id in the string itself like so:
async function getData(id) {
let url = `https://blablabla/moves/${id}`; // use string interpolation here
const fetchData = {
method: "PUT",
body: {
roomid: 2512,
move: "move 2",
id: 2,
},
headers: new Headers({
"Content-Type": "application/json; charset=UTF-8",
}),
};
await fetch(url, fetchData)
.then((response) => response.json())
.then((data) => console.log(data));
}
I have a function with two arrows, which sends some form data to my api via a POST request with fetch, once the form gets submitted. I want to make fetch asynchronous, but I really have no clue where the async keyword goes in this case.
//handles the submitting process
const handleSubmit = async (form_username, form_email, form_password) => (event) => {
event.preventDefault();
let data = {
username: form_username,
email: form_email,
password: form_password,
};
const response = await fetch(API + "/register", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(data),
});
};
The function would then be called via handleSubmit(param1, param2,...);
However, having the async keyword infront of the first params list returns the error unexpected reserved word 'await'
Any ideas where I should place the async keyword in order to actually make it async?
Thanks in advance!
Your async is declared on the wrong function: it should be the inner function that is being returned, since it is the one that contains the await keyword:
const handleSubmit = (form_username, form_email, form_password) => async (event) => {
// Rest of the logic here
}
I am new to react and I can fetch the data from JSON file . Now I need to update those values and submit to the JSON file . I am struggling to submit updated input field in JSON file
submitEmpData(event) {
event.preventDefault();
this.state.empProjects.allocation=this.state.allocation;
this.setState({
empProjects:this.state.empProjects
});
return fetch('http://localhost:3000/Employee/' + this.state.empProjects.id, {
method: 'PUT',
mode: 'CORS',
body: this.state.empProjects,
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
return res;
}).catch(err => err);
}
There are some ways to trigger a render in react:
You send new values down as props to a child component, or
You use a form of state (hooks or setState for example) to update a components state.
In your example, add a setState once the fetch promise has either rejected or resolved, setting the data needed for rendering.
I have restructured the code for better understanding. I believe JSON.stringify() and res.json() may places where you might need to look into.
async submitEmpData(event) {
event.preventDefault();
let { empProjects, allocation } = this.state;
empProjects.allocation = allocation;
// updating the state
this.setState({
empProjects,
});
// calling the api
try {
let res = await fetch("http://localhost:3000/Employee/" + this.state.empProjects.id, {
method: "PUT",
mode: "CORS",
body: JSON.stringify(this.state.empProjects),
headers: {
"Content-Type": "application/json"
}
})
return await res.json();
} catch (err) {
return err;
}
}
Kindly ping me in comments for any clarification
The following method is wrong to change the JSON because the this.state is an object and javascript will check the reference for comparison (See this).
this.state.empProjects.allocation=this.state.allocation;
this.setState({
empProjects:this.state.empProjects
});
instead of this, you can use the spread operator to create a new object:
this.setState({
...this.state, this.state.empProjects: { ...this.state.empProjects, allocation: "NEW value"}
})
Also to send the request using fetch, the body must match with content type:
body: JSON.stringify(this.state.empProjects)
Why formData goes empty to my express+mongodb server? I've some problems with querySelector and addEventListener, but for now thats ok. However, I don't find a way for sending all values of my form to the server. Please, someone help me?
document.querySelector('#enviar-
cadastro').addEventListener('click', Cadastrar);
Cadastrar('http://localhost:5000/usuario/novo')
.then(response => console.log(response.json()))
.then(data => console.log(data))
.catch(error => console.log(error));
function Cadastrar(url) {
const formDados = new FormData(document.querySelector('#signup'))
return fetch(url, {
method: 'POST',
body: JSON.stringify(formDados),
headers: {
"Content-Type": "application/json"
}
})
};
First of all console.log(formDados) inside Cadastrar and see what you get.
This should also help: https://code.lengstorf.com/get-form-values-as-json/
I'm starting to learn react-native and ran into some problems while using fetch on Android.
try {
let response = await fetch(REQUEST_URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
***parameters***
})
});
let responseJson = await response;
if(responseJson){
// console.log(responseJson);
console.log(responseJson.text());
// console.log(responseJson.json());
}
} catch(error) {
console.error(error);
}
The request is sent correctly but the answer isn't shown in it's totality:
(**loads more data before**){"ID":"779","DESCRICAO":"ZXCVB","CLIENTENUMERO":"10133","CLIENTENOME":"Lda 1","TREGISTO":"2015\\/11\\/24 09:34:15","TTERMO":"","SITUACAO":"C","TIPO":"P","NOTIFICACOES":"email","NOTIFI_TAREFA":"","ESFORCOS_TOT":"4","TEMPOGASTO_TOT":"0:01:44","TEMPOGASTO_PES":"0:01:44","PROJECTO":"New Products","USERNAME":"AT","UREGISTO":"S","EMCURSO":"0","TULTIMO":"2015\\/12\\/18 20:37:56","EQUIPA":"","NIVEL":"AVISAX"},{"ID":"783","DESCRICAO":"123","CLIENTENUMERO":"10133","CLIENTENOME":"Lda 1","TREGISTO":"2015\\/11\\/24 09:43:26","TTERMO":"","SITUACAO":"C","TIPO":"P","NOTIFICAC
As you can see, the JSON object isn't complete. Sending the same request using other methods in a browser returns the JSON correctly.
I'm wondering if this is an actual issue with fetch or with Android.
I've tried setting size and timeout parameters to 0 in fetch but it did nothing.
Edit: also tried using synchronous fetch instead of async, with the same effect:
fetch(REQUEST_URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
***params***
})
})
.then((response) => response.text())
.then((responseText) => {
console.log(responseText);
})
.catch((error) => {
console.warn(error);
}
Also tried:
console.log(responseJson);
and
console.log(responseJson.json());
Edit for further clarification:
When using response.json(), the response is shown as json (as to be expected) but it's still incomplete.
Edit :: Issue was with console.log limiting the number of characters it displays in the console.
Quick question:
Can you get the json object in its entirety if you hit the endpoint with postman? It could very well be your server/service that is cutting off the message.
Lastly, (and I see you mentioned this above) but I always use the 'json' method off the response obj when I know that is the notation type - which should return a promise.
fetch(REQUEST_URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
***params***
})
})
//get the response and execute .json
.then((r) => r.json())
//then listen for the json promise
.then((j) => {
console.log(j);
})
.catch((error) => {
console.warn(error);
}
Let me know what happens and if you get the full response with postman (or fiddler compose).