displaying text in web [closed] - html

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 days ago.
Improve this question
I am trying to print a element in an array(statusData 0 and 3) on the screen, but it does not work.
import { useEffect, useState } from 'react';
import '../styles.css';
function Status({ statusArr }) {
const test = {
ID: 'spoofer_001',
INFO: 'REPORT',
TYPE: 'INFO',
VALUE: {
ELAPSE: '0.0',
GENONOFF: 1,
LAT: 35.210571916195157,
LNG: 129.37419937688139,
SDRONOFF: 1,
},
};
const statusData = [];
const printData = (data) => {
for (var i in data) {
if (typeof data[i] === 'object') {
statusData.push('ELAPSE: ' + data[i]['ELAPSE']);
statusData.push('GENONOF: ' + data[i]['GENONOF']);
statusData.push('SDRONOFF: ' + data[i]['SDRONOFF']);
} else {
statusData.push(i + ': ' + data[i]);
}
}
};
return (
<>
<span>{statusData[0]}</span>
<span>{statusData[3]}</span>
{/* {Object.keys(test).map((keyName, index) => (
<>
<span>
{keyName} :{' '}
{typeof test[keyName] === 'object'
? test[keyName]['ELAPSE']
: test[keyName]}
</span>
<br />
</>
))} */}
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
</div>
</>
);
}
export default Status;
I thought that
{statusData[0]}
{statusData[3]}
these lines would print them, but it would not.
Could someone explain why?

Related

TypeError: allOrg.map is not a function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I am trying to loop through all the objects in a array state in react, hence I used map function. Here is the block of code where I used the map function:
return(
<div>
<Navbar/><br/>
{
allOrg.map((data: orgType, index: number) => {
/*<Org key={index} userId = {UserId} orgName = {data.orgName} /> */
<h1>{index} {UserId} {data.orgName}</h1>
})
}
<div className = "OrgRow">
<button className = "OrgTeams" onClick={createOrg}>Add Org</button>
{createOrgForm}
</div>
</div>
)
But it is showing me "TypeError: allOrg.map is not a function" error. picture of the error I looked for similar errors on stackoverflow, but only suggestions were that map can only be used with arrays. And here my state is an array only, still this problem is persisting. Here is my declaration of the state named "allOrg":
import React,{useState, useEffect} from "react";
import { useForm } from "react-hook-form";
import Navbar from "./navBar";
import Org from "./org";
import "../../style/auth.css";
import "../../style/home.css";
interface orgType{
orgId: string;
orgName: string;
}
function Home(): JSX.Element{
//let UserId: string = "Ronak";
const initialOrg = {
orgId: "",
orgName: ""
}
const [UserId, setUserId] = useState<string>("userId");
const [createOrgForm, setForm] = useState(<div></div>);
const [allOrg, setAllOrg] = useState<orgType[]>([initialOrg]);
const [orgAdded, changeState] = useState(true);
const {register, handleSubmit} = useForm();
I am also pasting images containing my entire code for that component:
import React,{useState, useEffect} from "react";
import { useForm } from "react-hook-form";
import Navbar from "./navBar";
import Org from "./org";
import "../../style/auth.css";
import "../../style/home.css";
interface orgType{
orgId: string;
orgName: string;
}
function Home(): JSX.Element{
//let UserId: string = "Ronak";
const initialOrg = {
orgId: "",
orgName: ""
}
const [UserId, setUserId] = useState<string>("userId");
const [createOrgForm, setForm] = useState(<div></div>);
const [allOrg, setAllOrg] = useState<orgType[]>([initialOrg]);
const [orgAdded, changeState] = useState(true);
const {register, handleSubmit} = useForm();
const submitButton = {
margin: "auto",
marginTop: 30,
display: "block"
}
useEffect(() => {
fetch('/api/v1/auth/verifyJWT', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => {
console.log(data.serviceResponse.userId);
setUserId(data.serviceResponse.userId);
console.log(UserId);
}
)
}, [] )
useEffect( () => {
console.log(UserId);
fetch('/api/v1/org/all/' + UserId)
.then(res => res.json())
.then(data => {
setAllOrg(data);
console.log("Hi");
console.log(data);
console.log(allOrg);
console.log("bye");
}
)}, [UserId]);
function onSubmit(data: any){
fetch('/api/v1/org/create', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => {
console.log(data);
if(data.message == "Created!"){
console.log("successful");
setForm(()=><div></div>);
changeState(!orgAdded);
}
else{
console.log("failed");
}
})
}
function createOrg(){
console.log(UserId);
setForm(()=>
<form className = "auth_form" onSubmit = {handleSubmit(onSubmit)}>
<br/><br/>
<input className = "auth_input" {...register("userId", {required: true})} name="userId" value={UserId}/>
<br/>
<input className = "auth_input" {...register("orgName", {required: true})} name="orgName" placeholder="Organization Name"/>
<br/>
<button className = "auth_button" style={submitButton} type="submit">Create</button>
</form>
)
}
return(
<div>
<Navbar/><br/>
{
allOrg.map((data: orgType, index: number) => {
/*<Org key={index} userId = {UserId} orgName = {data.orgName} /> */
<h1>{index} {UserId} {data.orgName}</h1>
})
}
<div className = "OrgRow">
<button className = "OrgTeams" onClick={createOrg}>Add Org</button>
{createOrgForm}
</div>
</div>
)
}
export default Home;
Line 103 is where I used allOrg.map() and the declaration of allOrg state is at the start of the function.
Any help would be welcome.
P.S. Incase anyone thinks that the allOrg state might be empty, it is not so. I checked using console.log..
Edit: I am adding the ss of console.log of allOrg, console.log(allOrg).
Even if you checked that allOrg is state is not empty it might be possible that component is rendered multiple times where first time allOrg is at initial state for second rendering it might be empty or null or undefined and at last when API call is completed it fills allOrg.
So you have to handle case for when allOrg is null or something.
let orgList;
if(Array.isArray(allOrg)){
orgList = allOrg.map(
...
);
}
render (
...
{orgList}
...
);

How to properly use an autocomplete input field based on a database source in Vue?

I want to use an input field (or something similar) that suggests an autocomplete, based on records from a data source.
In Vue I retrieve an array from a database table containing 3000+ records:
data(){
return{
inboundRelation_Trelation_data: [],
}
},
mounted(){
axios.get('/app/wms/allRelations', {
params: {
"dbConn": this.connString,
}
})
.then(response => this.inboundRelation_Trelation_data = response.data);
},
Based on this data, I want an autocomplete input field and/or dropdown. I've found 2 approaches online.. 1:
<select v-model="form.CUSTOMER_NAME">
<option v-for="(relation, index) in inboundRelation_Trelation_data" :value="relation.RELATIONCODE" v-text="relation.COMPANYNAME + ' | ' + relation.RELATIONCODE"></option>
</select>
This populates a dropdown, but my users experience this as tedious, as they need to type their letters quickly, otherwise after a small pause (like <0.5s), the next typed letter will start a new search and the results are inconsistent.
The other approach is using a data-list:
<input list="allRelations" type="text" #focus="$event.target.select()" v-model="form.CUSTOMER_NAME">
<datalist id="allRelations">
<option v-for="(relation, index) in inboundRelation_Trelation_data" :value="relation.RELATIONCODE" v-text="relation.COMPANYNAME + ' | ' + relation.RELATIONCODE"></option>
</datalist>
This works perfectly for small amounts of data. But when dealing with 100+ records (or 3000+ in this case), the whole browser freezes upon typing a letter. For some reason this is a very resource-heavy implementation. I've found some people with similar issues, but no solutions.
At the end of the day, I just want my users to be able to search in a huge list of 3000+ records. How do I approach this?
You can use vue-autosuggest package by this github link :
https://github.com/darrenjennings/vue-autosuggest
I am using this package and my data loads as my expect.
This is the template that you can use:
<template>
<div class="autosuggest-container">
<vue-autosuggest
v-model="form.CUSTOMER_NAME"
:suggestions="filteredOptions"
#focus="focusMe"
#click="clickHandler"
#input="onInputChange"
#selected="onSelected"
:get-suggestion-value="getSuggestionValue"
:input-props="{
class: 'form-control',
id: 'autosuggest__input',
field: 'CUSTOMER_NAME',
placeholder: 'Enter customer name for auto suggest',
}"
>
<div
slot-scope="{ suggestion }"
style="display: flex; align-items: center"
>
<img
:style="{
display: 'flex',
width: '25px',
height: '25px',
borderRadius: '15px',
marginLeft: '10px',
}"
:src="suggestion.item.avatar"
/>
<div style="{ display: 'flex', color: 'navyblue'}">
{{ suggestion.item.CUSTOMER_NAME }}
</div>
</div>
</vue-autosuggest>
</div>
And the Script section:
<script>
export default {
data() {
return {
searching: false,
query: '',
selected: '',
suggestions: [],
}
},
computed: {
filteredOptions() {
return [
{
data: this.suggestions.filter((option) => {
return (
option.name.toLowerCase().indexOf(this.query.toLowerCase()) > -1
)
}),
},
]
},
},
methods: {
clickHandler() {
//
},
onSelected(item) {
this.selected = item.item
},
async onInputChange(text = '') {
this.searching = true
await this.$axios
.get(`/app/wms/allRelations`,{
params: {
"dbConn": this.connString,
})
.then((res) => {
this.suggestions = res.data.data
})
.catch((e) => console.log(e))
.finally(() => (this.searching = false))
},
getSuggestionValue(suggestion) {
return suggestion.item.name
},
focusMe(e) {
this.onInputChange()
},
},
}
</script>
If still your browser freeze, you have to change your API response limit to something like descended 10 items.

TypeError: JSON.stringify(...).then is not a function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am new to react and having a problem. What I want to do is that I want to add departments to a table that I created through the web api created in visual studio. I want to add the department through the modal pop up. However, I am having an issue. Whenver, I click the add button it gives me this error.
TypeError: JSON.stringify(...).then is not a function
handleSubmit
D:/React/employee-app/src/components/AddDepModal.js:22
19 | 'Content-Type':'application/json'
20 |
21 | },
> 22 | body: JSON.stringify({
| ^ 23 | DepartmentID:null,
24 | DepartmentName: event.target.DepartmentName.value
25 | })
View compiled
Here is my code where I call the 'POST' method
export class AddDepModal extends Component{
constructor(props){
super(props);
}
handleSubmit(event){
event.preventDefault();
fetch('https://localhost:44363/api/Department',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
},
body: JSON.stringify({
DepartmentID:null,
DepartmentName: event.target.DepartmentName.value
})
.then(res=> res.json())
.then((result)=>
{
alert(result);
},
(error)=>{
alert('Failed')
}
)
}
)
}
Here is the part which I render on the screen(might not be required):
render(){
return(
<Modal
{...this.props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
Add Department
</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="container">
<Row>
<Col sm={6}>
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="DepartmentName">
<Form.Label>Department Name</Form.Label>
<Form.Control
type = "text"
name="DepartmentName"
required
placeholder="Department Name"
/>
</Form.Group>
<Form.Group>
<Button variant="primary" type ="submit">
Add Department
</Button>
</Form.Group>
</Form>
</Col>
</Row>
</div>
</Modal.Body>
<Modal.Footer>
<Button variant= "danger" onClick={this.props.onHide}>Close</Button>
</Modal.Footer>
</Modal>
);
}}
export default AddDepModal;
I am not understanding what the error is?
You should use fetch like this
fetch('https://localhost:44363/api/Department', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
DepartmentID: null,
DepartmentName: event.target.DepartmentName.value
}),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
I think you are missing a ).
In your example you are calling then(..) function on the return value of JSON.stringify(...)

How to check if JSON data matches a particular string in React js?

I want to check if data retrieved from JSON server matches a particular string in ReactJS. I am using PrimeReact to draw table and graph This is my code:
import React from 'react';
import {DataTable} from 'primereact/datatable';
import {Column} from 'primereact/column';
import {Dialog} from 'primereact/dialog';
import {Button} from 'primereact/button';
import {Chart} from 'primereact/chart';
import './style.css';
export default class TerminalData extends React.Component {
constructor() {
super();
this.state = {
isLoaded: false,
visible: false
};
}
componentDidMount() {
fetch('https://api.myjson.com/bins/80ao2')
.then((response) => response.json())
.then((findresponse) =>{
this.setState({
jsonData: findresponse.root,
isLoaded: true
})
})
}
onClick() {
this.setState({ visible: true });
}
onHide() {
this.setState({visible: false});
}
displaySelection(data) {
if(!data || data.length === 0) {
return <div style={{textAlign: 'left'}}>Click any above to view details</div>;
}
else {
if(data instanceof Array)
return <ul style={{textAlign: 'left', margin: 0}}>{data.map((browseData,i) => <li key={browseData.serialNo}>{'Blocked URLs: ' + browseData.blockedURLs + ' ,Unblocked URLs: ' + browseData.UnblockedURLs + ' ,Other URLs: ' + browseData.otherURLs}</li>)}</ul>;
else
return <div style={{textAlign: 'left'}}>Selected user: {data.blockedURLs+ ' - ' + data.UnblockedURLs + ' - ' + data.otherURLs }</div>
}
}
render() {
let sarjapur=0,kodathi=0,ec=0,whitefield=0;
const barData = {
labels: ['Sarjapur', 'Kodathi', 'EC', 'WhiteField'],
datasets: [
{
label: 'Dataset',
backgroundColor: '#42A5F5',
data: [sarjapur,kodathi,ec,whitefield]
}
]
};
if(this.state.isLoaded === true)
{
for (let i = 0; i < this.state.jsonData.length; i++)
{
if(this.state.jsonData[i].location === "Sarjapur")
{
sarjapur = sarjapur++;
}
else if(this.state.jsonData[i].location === 'Kodathi')
{
kodathi = kodathi++;
}
else if(this.state.jsonData[i].location === 'EC')
{
ec = ec++;
}
else if(this.state.jsonData[i].location === 'WhiteField')
{
whitefield = whitefield++;
}
}
console.log("location" +sarjapur + kodathi + ec + whitefield);
}
return (
<div>
{ this.state.isLoaded ?
<div>
<DataTable value={this.state.jsonData} selectionMode="single" footer={this.displaySelection(this.state.selectedUser1)}
selection={this.state.selectedUser1} onSelectionChange={e => this.setState({selectedUser1: e.value.user_activity})}>
<Column field="serialNo" header="Serial No." />
<Column field="userName" header="Username" />
<Column field="location" header="Location" />
</DataTable>
<Dialog header="Chart" visible={this.state.visible} style={{width: '40vw'}} onHide={this.onHide.bind(this)} maximizable>
<Chart type="bar" data={barData} />
</Dialog>
<Button label="Show Chart" icon="pi pi-external-link" onClick={this.onClick.bind(this)} />
</div>
: "Loading... Please Wait"}
</div>
);
}
}
See the IF condition block
I was checking using If condition but it does not work and outputs 0. I checked individually using console.log(this.state.jsonData[1].location); I am getting its value from Json but when i compare it, if condition fails. I also tried it by setting state instead of using var but same result. Here is JSON data if anyone wants to see http://myjson.com/80ao2.
What i am trying to achieve is that how frequent a particular word appears and increase the count simultaneously and according to that draw graph. How to achieve this? OR is it not a good approach? Please suggest a better way if i can do this?
Problem is you are not doing increment properly
sarjapur++ // post-increment
change it to
++sarjapur // pre-increment

Show title and featured image from WordPress REST API with React Native

I'm trying to get the titles and featured images from several pages that are included in a JSON response. After searching for a while and trying something, I'm getting stuck on displaying the required elements. The code on the React Native side looks like this:
https://snack.expo.io/#jvdl2711/artists
I found a way to display my data in the desired order and style. Unfortunately, each 'post' should be clickable to navigate to other screens and visualize those individual posts, but I don't know how because the objects are rendered different than expected at the moment. Is there any way how to solve this?
The problem with your approach is that you're are not iterating your data.
So to create the wanted behaviour you need to use something similar to this (you need to fix the style according to your specs):
(I've added a loading indicator and a simple error handling to this example, also you need to add a default image cause I've noticed some items with no thumbs)
import React, {Component} from 'react';
import {
View,
Text,
FlatList,
StyleSheet,
Image,
ActivityIndicator,
} from 'react-native';
export default class Home extends Component {
state = {
data: [],
isLoading: true,
isError: false,
}
componentWillMount() {
fetch('http://54.168.73.151/wp-json/wp/v2/pages?parent=38&per_page=100')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson,
isLoading: false,
isError: false
})
})
.catch((error) => {
this.setState({
isLoading: false,
isError: true
})
console.error(error);
});
}
renderRow = (item) => (
<View>
<Image
style={styles.thumb}
source={{uri: item.better_featured_image ? item.better_featured_image.source_url : 'url to a default image'}}
/>
<Text style={styles.title}>{item.title.rendered}</Text>
</View>
)
getKey = (item) => String(item.id)
renderComponent() {
if (this.state.isLoading) {
return (
<ActivityIndicator/>
)
} else if (this.state.isError) {
return (
<Text>Error loading data</Text>
)
} else {
return (
<FlatList
data={this.state.data}
renderItem={({item}) => this.renderRow(item)}
keyExtractor={this.getKey}
/>
)
}
}
render() {
return (
<View style={styles.container}>
{this.renderComponent()}
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
thumb: {
height: 100,
width: 100,
resizeMode: 'cover',
},
})