Condition for selecting an object in body: JSON.stringify () - javascript

I ask for your help in writing the conditions for selecting an object in JSON.stringify ().
How can i do this?
this.props.a > 7;
this.props.b > 7
onSubmit = (e) => {
e.preventDefault();
this.props.x(this.state.y);
const user1 = {
name: "John",
age: 30
};
const user2 = {
name: "Vasya",
age: 27
}
fetch('URL', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body:JSON.stringify (How can I write something with a similar meaning
this.props.a>7 ? USER1:USER2 )
});
}

How about
body: ( this.props.a>7 ? JSON.stringify(USER1) : JSON.stringify(USER2) )

Related

Update specific row in google sheets based on ID value

I am working on a project for a Chrome Extension I am creating where it uses Google Sheets as a "database". I have the create and get part down. However, I am struggling with the update part. Here is my code so far:
let init = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json'
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_ID}/values/All Escalations!A5:Z10000001",
init)
.then((data) => {
return data.json();
}).then ((completedata) => {
const numRows = completedata.values ? completedata.values.length: 0
console.log(`${numRows} rows retrieved`)
let source = completedata.values;
const input = source.filter(function (row, index) {
row.unshift(index);
return row;
}).filter(function (iRow) {
return iRow[1] === arcaseiddis;
});
var index = (input[1]) ; //Saves the old index
let arjira2 = document.getElementById('jiracard').value
let ardatesubmitteddis2 = document.getElementById('datesubmitted').value
let arsubmittedbydis2 = document.getElementById('submittedbyaredit').value
let arclientiddis2 = document.getElementById('clientidaredit').value
let arcasenumberdis2 = document.getElementById('casenoaredit').value
let arnotesdis2 = document.getElementById('notesaredit').value
let arstatusdis2 = document.getElementById('statusaredit').value
let arissuedis2 = document.getElementById('casedesaredit').value
let arassignedtodis2 = document.getElementById('assignedtoaredit').value
let datearcompleted = document.getElementById('datecompletearedit').value
let arcaseiddis2 = e.target.parentElement.dataset.id
input[0]= arcaseiddis2; //Update the row with stuff
input[1] = arcasenumberdis2;
input[2]= arjira2;
input[3]= arstatusdis2;
input[4]= arissuedis2;
input[5]= arclientiddis2;
input[6]= ardatesubmitteddis2;
input[7]= arsubmittedbydis2;
input[8]= arassignedtodis2
input[9]= datearcompleted
input[10]= arnotesdis2
let values = [
[
input[0],
input[1],
input[2],
input[3],
input[4],
input[5],
input[6],
input[7],
input[8],
input[9],
input[10]
]
];
const resource = {
values
};
console.log(values)
I am able to console.log this out and it actually shows the updates I put in. However, when I run the update function it gives the following error:
{range: "All Escalations!Aundefined:Jundefined", values: {values: [,…]}}
range
:
"All Escalations!Aundefined:Jundefined"
values
:
{values: [,…]}
values
:
[,…]
0
:
["82389566743686", "4306203", "None", "SUBMITTED", "Testing", "Client", "2/8/2023", "John SMith",…]
0
:
"82389566743686"
1
:
"4306203"
2
:
"None"
3
:
"SUBMITTED"
4
:
"Testing"
5
:
"Client"
6
:
"2/8/2023"
7
:
"John Smith"
8
:
"Carey Jones"
9
:
""
10
:
"No Notes Yet"
This is the update function I am running:
var payload = {
"range": "All Escalations!A" + index + ":J" + index,
"values": resource
}
let init = {
method: 'PUT',
async: true,
headers: {
Authorization: 'Bearer ' + token,
},
body: JSON.stringify(payload)
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/{SpreadsheetID}/values/All Escalations/?valueInputOption=USER_ENTERED",
init)
})
The code I've used so far is mainly coming from this article: google sheets api v4 update row where id equals value
Because this is a Chrome Extension I can't connect to the api via the URL like we used to in MV2. So I do it via the "fetch" method and it works for the get part. From looking over the above article, it looks like the person does the "get" to get that specific row. Then updates the specific row based on the ID. I appreciate any help I can get.
With some tinkering around I found the answer:
I credit Take A Minute with getting me in the right direction with his snippet. google sheets api v4 update row where id equals value. I am just starting out at this so any input on how to make this more efficient is welcome.
function updatearescalation(){
chrome.identity.getAuthToken({ 'interactive': true }, getToken);
function getToken(token) { // this seems to be the best way to get the token to be able to make these requests.
let initdarread = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json'
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1uXGfr5OvJjW2Pb9YhkbLHED3cQcJI5YsvJKLedAHRKY/values/All Escalations!A5:Z10000001",
initdarread)
.then((data) => {
return data.json();
}).then ((completedata) => {
const numRows = completedata.data ? completedata.data.length: 0
console.log(`${numRows} rows retrieved`)
source = completedata.values;
const input = source.filter(function (row, index) {// when I use the source.map it returns a random row instead of the specific row I want.
row.unshift(index);
return row;
}).filter(function (iRow) {
return iRow[1] === arcaseiddis;
});
var index = parseInt(input[0]) + 5; //Saves the old index The +5 indicates where the actual data starts. This is important.
input[0].shift(); //According to post previously mentioned this removes the old index.
input[0] // This is where you update the rows with what you want.
let values = [
input[0], // This is where all the values you want updated go.
];
const resource = {
values
};
var payload = {
"range": "All Escalations!A" + index + ":K" ,
"values": resource
}
let range = "All Escalations!A" + index + ":K"
let initarupdate = {
method: 'PUT',
async: true,
headers: {
Authorization: 'Bearer ' + token,
},
body: JSON.stringify(payload)
};
fetch(
`https://sheets.googleapis.com/v4/spreadsheets/1uXGfr5OvJjW2Pb9YhkbLHED3cQcJI5YsvJKLedAHRKY/values/${range}/?valueInputOption=USER_ENTERED`,
initarupdate)
}) // I used a literal here to be able to use the Range I put in the payload.
}
}

post request without a form or a button in React?

So I have to make a post request without a form or a button. I have the patientInfo array that is rendered on a table. When the user chooses a location for a patient, then that patient will have a timestamp value. When the patient in the array has a timestamp that's when I am supposed to auto post the patient with the timestamp.
My handleAutoObsSubmit() is kinda working but the problem is, it maps over the patienArray and sends the patient multiple time so if the user chooses the third patient's location, there will be three object of the same patient that is sent.
Another issue I am having with is componentDidUpdate, it sends the post request every second. I suspect that is because the patient count is being count down every sec. Not 100% sure though. Is it even a good idea to send post request in componentDidUpdate?
patientInfo = [
{ count: 100, room: "1", name: 'John Nero', timeStamp: '', location: ''},
{ count: 100, room: "2", name: 'Shawn Michael', timeStamp: '', location: ''},
{ count: 100, room: "3", name: 'Gereth Macneil', timeStamp: '', location: ''}
]
handleAutoObsSubmit = () => {
const postUrl = '/send_patient_that_has_timeStamp';
const timeStampedPatients = this.state.patientInfo.filter(patient => patient.timeStamp !== '');
let data = {};
timeStampedPatients.map((patient) => {
data = {
room: patient.room,
patient: patient.name,
timestamp: patient.timeStamp,
location: patient.locationInfo,
};
});
fetch(postUrl, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then((res) => {
if (!res.ok) {
console.log('request failed');
} else {
console.log('request sent');
}
});
}
componentDidUpdate() {
this.state.patientInfo.map(patient => {
if (patient.timeStamp !== '') {
this.handleAutoObsSubmit();
}
});
}
componentDidMount() {
this.countDownInterval = setInterval(() => {
this.setState(prevState => ({
patientInfo: prevState.patientInfo.map((patient) => {
if (patient.locationInfo!== '') {
if (patient.count <= 0) {
clearInterval(this.countDownInterval);
}
return { ...patient, count: patient.count - 1 };
}
return patient;
})
}));
}, 1000);
}
You should be able to handle it in a similar fashion to this:
function Table() {
const [tableData, setTableData] = React.useState([
{
name: "John Doe",
timestamp: ""
},
{
name: "Jane Doe",
timestamp: ""
},
{
name: "Nancy Doe",
timestamp: ""
}
]);
const updateItem = (event, index) => {
let newstate = [...tableData];
newstate[index].timestamp = (new Date(Date.now())).toString();
alert(`Do POST here: ${JSON.stringify(newstate[index],null,2)}`);
setTableData(newstate);
};
return (
<table border="5">
<tr>
<th>
<div>Patient</div>
</th>
<th>
<div>Timestamp</div>
</th>
<th>Update</th>
</tr>
{tableData.map((item, index) => {
return (
<tr>
<td>{item.name}</td>
<td style={{width:'410px'}}>{item.timestamp}</td>
<td>
<button
style={{backgroundColor:'green', color:'white'}}
onClick={event => updateItem(event, index)}>
UPDATE
</button>
</td>
</tr>
);
})}
</table>
);
}
ReactDOM.render(<Table />, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>

Displaying Fetch Data and Rendering - React JS

I am able to save data into my database. However, i want to know how to show/render the fetch data on my screen after i run my fetch request.
When i add data i am able to push to render on my page. But what i want is, once i run my fetch data function, how do i render the response that i get onto my screen ?
My Json data after fetch looks like this when i console.log(json.data.shipping)
0: { name: "Samsung A10", phone: "001-2342-23429"}
1: {name: "Iphone Xs", phone: "001-12193-1219"}
PS: Beginner with React JS
Below is how i save data
state = {
shippings: userData,
addNewData: {
name: '',
phone: ''
},
};
addData() {
const { name,phone} = this.state.addNewData;
if (name!== '' && phone = "") {
let newData = {
...this.state.addNewData,
id: new Date().getTime()
}
let shippings = this.state.shippings;
fetch( 'http://facicla:5000/api', {
method:'post',
/* headers are important*/
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
body: JSON.stringify(this.state.addNewData)
})
.then(response => {
return response.json();
shippings.push(newData);
NotificationManager.success('Sucess!');
})
}
}
userData
export default [
{
name: 'Shipping-Car',
phone: '001-72342-2342',
} ]
Fetch Data
fetchAllData(){
return this.fetchPost().then(([response,json]) => {
if(response.status === 200)
{
console.log(json.data.shipping)
0: { name: "Samsung A10", phone: "001-2342-23429"}
1: {name: "Iphone Xs", phone: "001-12193-1219"}
}
})
}
fetchPost(){
const URL = 'http://facicla:5000/api';
return fetch(URL, {method:'GET',headers:new Headers ({
'Accept': 'application/json',
'Content-Type': 'application/json',
})})
.then(response => Promise.all([response, response.json()]));
}
Render
render() {
const { shippings, addNewData} = this.state;
return (
<div className="wrapper">
<div className="row row-eq-height">
{shippings.map((shipping, key) => (
<div className="col-sm-3 col-md-3 col-lg-3" key={key}>
<div className="d-flex justify-content-between">
<h5 className="fw-bold">{shipping.name}</h5></a>
<h5 className="fw-bold">{shipping.phone}</h5></a>
</div>
</div>
))}
</div>
}
Try this:
fetchAllData(){
return this.fetchPost().then(([response,json]) => {
if(response.status === 200)
{
console.log(json.data.shipping)
this.setState(
{ shippings: Object.values(json.data.shipping)
//or shippings: json.data.shipping
}
)
//0: { name: "Samsung A10", phone: "001-2342-23429"}
//1: {name: "Iphone Xs", phone: "001-12193-1219"}
}
})
}

Twitch API returning info in wrong order using Array.map()

I'm calling the Twitch API (should mention I'm doing this in React) to get information on a few channels. I'm getting the data back, but it gets added to the array in the wrong order, different on every reload. Since I have two make two different calls, this ends up leaving me with mismatched information. I'm assuming it's because some calls take longer than other, and array.map() is running regardless if the first call was done yet, I'm just not sure how to fix that.
Here is my script:
export default class TwitchApp extends React.Component {
state = {
games: [],
statuses: [],
names: [],
logos: [],
streams: ["nl_kripp", "ESL_SC2", "Day9tv",
"DisguisedToastHS" ]
};
findStreams = () => {
const channels = this.state.streams;
const statusUrls = channels.map((channel) => {
return 'https://api.twitch.tv/kraken/streams/' + channel;
})
const infoUrls = channels.map((channel) => {
return 'https://api.twitch.tv/kraken/channels/' + channel;
})
statusUrls.map((statusUrl)=> {
let url = statusUrl;
return $.ajax({
type: 'GET',
url: url,
headers: {
'Client-ID': 'rss7alkw8ebydtzisbdbnbhx15wn5a'
},
success: function(data) {
let game;
let status = data.stream != null ? "Offline" : "Online";
this.setState((prevState)=> ( { statuses: prevState.statuses.concat([status]) } ) );
status = '';
}.bind(this)
});
});
infoUrls.map((url)=> {
return $.ajax({
type: 'GET',
url: url,
headers: {
'Client-ID': 'rss7alkw8ebydtzisbdbnbhx15wn5a'
},
success: function(data) {
let name = data.display_name != null ? data.display_name : 'Error: Can\'t find channel';
let logo = data.logo != null ? data.logo : "https://dummyimage.com/50x50/ecf0e7/5c5457.jpg&text=0x3F";
let game = data.game != null ? data.game : "Offline";
//let status = data.status != null ? data.status: "Offline";
this.setState((prevState)=> ( { games: prevState.games.concat([game]), names: prevState.names.concat([name]), logos: prevState.logos.concat([logo]) } ) );
game = '';
logo = '';
name = '';
}.bind(this)
});
});
};
You have really many options here...
could either look into AsyncJs and it is the async.series(); you are looking for, that will make all call go into specific order.
You could also go for a promised based HTTP requester, like Axios in which you can chain all your requests.
But really, I would go with the 3rd option which is that you make an array of objects as your state like this:
state = {
info: {
"nl_kripp": {
game: '',
status: '',
name: '',
logo: '',
},
"ESL_SC2": {
game: '',
status: '',
name: '',
logo: '',
},
"Day9tv": {
game: '',
status: '',
name: '',
logo: '',
},
"DisguisedToastHS": {
game: '',
status: '',
name: '',
logo: '',
}
},
streams: ["nl_kripp", "ESL_SC2", "Day9tv", "DisguisedToastHS"]
};
and do something like this:
var streams = this.state.streams;
var fetchedArray = [];
fetchedArray.map(streams , stream => {
let url = 'https://api.twitch.tv/kraken/streams/' + stream;
return $.ajax({
type: 'GET',
url: url,
headers: {
'Client-ID': 'rss7alkw8ebydtzisbdbnbhx15wn5a'
},
success: function(data) {
var currentState = Object.assign({}, this.state.info[stream]);
currentState.status = data.stream === null ? 'Offline' : 'Online';
currentState.name = data.display_name;
currentState.logo = data.channel.logo;
currentState.game = data.game;
}.bind(this)
});
});
Now fetchedArray will hold the same information but stacked together and easily handle with javascript after, rather than unsorted arrays.

select2 not selecting with no errors in the console

The dropdown list renders properly but when clicked on a dropdown result, nothing happens. I know that select2 expects the results to be in a certain way but couldn't figure out why the results won;t get selected when clicked on the result in the dropdown. No errors or anything in the console..
The response from the REST service is an array of objects with Person details.
Here's a jsfiddle that I have setup to illustrate the problem: https://jsfiddle.net/qygpb1Lr/
const $select2 = this.$element.find((`[rel='${this._interestedPartySelect2_id}']`));
const formatResult = person => {
if (!person || !person.FULL_NAME) return '';
return `
<strong>${person.LAST_NAME}, ${person.FIRST_NAME}</strong>
<br />
<i class='txt-color-cernerPurple'>${person.JOBTITLE || '--'}</i>
<br />
<span style="color:#525564">${person.DEPARTMENT || '--'}</span>
<br />
<span class='text-muted'>${person.INTERNET_E_MAIL || '--'}</span>
`;
};
const formatSelection = person => {
if (!person || !person.LAST_NAME || !person.FIRST_NAME) return '';
return `${person.LAST_NAME}, ${person.FIRST_NAME}`;
};
$select2.select2({
placeholder : 'Enter Last Name',
allowClear : true,
minimumInputLength : 3,
query: query => {
$.ajax({
url : `/remedy/people/last_name/${query.term}`,
type : 'GET',
headers: { 'content-type': 'application/json' },
data : JSON.stringify({ searchTerm: query.term })
})
.done(people => {
query.callback({ results: people });
});
},
formatResult,
formatSelection,
escapeMarkup : m => m
})
.on('select2-removed', e => {
// TODO
})
.on('select2-selecting', e => {
console.log(e); // TODO: Remove this
if (e.object && e.object.PERSON_ID) {
console.log(e.object.PERSON_ID); // TODO
}
});
I resolved this myself by passing an ID field to the select2 options like-so:
$select2.select2({
placeholder : 'Enter Last Name',
allowClear : true,
minimumInputLength : 3,
id: obj => obj.PERSON_ID,
query: query => {
$.ajax({
url : `/remedy/people/last_name/${query.term}`,
type : 'GET',
headers: { 'content-type': 'application/json' },
data : JSON.stringify({ searchTerm: query.term })
})
.done(people => {
query.callback({ results: people });
});
},
formatResult,
formatSelection,
escapeMarkup : m => m
})
.on('select2-removed', e => {
// TODO
})
.on('select2-selecting', e => {
console.log(e); // TODO: Remove this
if (e.object && e.object.PERSON_ID) {
console.log(e.object.PERSON_ID); // TODO
}
});

Categories