I am trying to parse the input xml data to json in react with the help of xml2js.
import React, { useState } from "react";
import xml2js from "xml2js";
function Parser() {
const [xmlData, setXmlData] = useState({});
let parser = new xml2js.Parser();
parser.parseString(
`<email>
<to>Test</to>
<from>Test1</from>
<heading>Test email</heading>
<body>Email regards to xml data parsing in React</body>
</email>`,
function (err, result) {
console.log(result);
if (result) {
setXmlData(result);
return;
}
return;
}
);
return (
<div>
Parse XML using ReactJs
{JSON.stringify(xmlData)}
</div>
);
}
export default Parser;
But I am getting unlimited re render error. Can anyone help on this ?
Thanks in advance
Since parseString is an asynchronous API, you will need to call it in an useEffect hook with the input data set as a dependency to avoid it being re-re-re-re-...-called on each render.
I also moved the input data to a prop here, for reusability.
import React, { useState } from "react";
import xml2js from "xml2js";
function Parser({ inputData }) {
const [xmlData, setXmlData] = React.useState(null);
React.useEffect(() => {
const parser = new xml2js.Parser();
parser.parseString(inputData, function (err, result) {
setXmlData(result);
});
}, [inputData]);
return (
<div>
Parse XML using ReactJs
{JSON.stringify(xmlData)}
</div>
);
}
export default Parser;
<Parser inputData={`<email>
<to>Test</to>
<from>Test1</from>
<heading>Test email</heading>
<body>Email regards to xml data parsing in React</body>
</email>`}
/>
Related
App.js File this is App.js file, Please check the below code and correct me I don't have any idea how to solve this issue. Thank you in advance.
.doc("2E3kDAa0QzqoQuoBK1T9", "vROxKUSgcNWwlt7cDEKV") on this line I get the issue.
import React, { useState, useEffect } from "react";
import { View, Text } from 'react-native';
import firestore from '#react-native-firebase/firestore';
function App() {
const [myData, setMyData] = useState(null);
useEffect(() => {
getDatabase();
}, []);
const getDatabase = async () => {
try {
const data = await firestore()
.collection('myCollection')
.doc("2E3kDAa0QzqoQuoBK1T9", "vROxKUSgcNWwlt7cDEKV")
.get();
setMyData(data._data)
} catch (err) {
console.log(err);
}
};
return (
<View>
<Text>First:-{myData ? myData.name : 'Loading...'}</Text>
<Text>Second:-{myData ? myData.secondData : 'Loading...'}</Text>
</View>
);
}
export default App;
This doesn't work:
.doc("2E3kDAa0QzqoQuoBK1T9", "vROxKUSgcNWwlt7cDEKV")
If you check the API docs for CollectionReference.doc it expects:
doc(documentPath?: undefined | string): DocumentReference<>;
So you can pass in a single document ID or path, not multiple.
If you want to return multiple documents by their ID, you can use th in query operator on the FieldPath.documentId() to do so for up to 10 values. If you have more values, you'll need to retrieve them in batches of up to 10 and merge them in your application code.
Hello I am trying to parse input xml data to json in react with xml2js, based on sample I found here.
I don't understand why is it running 4 times in console?
Why its reading only the first XML Inputdata?
Can anyone help me please?
Here is my code and the picture with failure.
App.js
import React from "react"
import Parser from "./Parser"
export default function App() {
return (
<div>
<Parser inputData={`<email>
<to>Test</to>
<from>Test</from>
<heading>Test email</heading>
<body>Email regards to xml data parsing in React</body>
</email>
<email>
<to>Test1</to>
<from>Test1</from>
<heading>Tes1t email</heading>
<body>1 Email regards to xml data parsing in React</body>
</email>`}/>
</div>
)
}
Parser.js
import React, { useState } from "react";
import xml2js from "xml2js";
function Parser({ inputData }) {
const [xmlData, setXmlData] = React.useState(null);
React.useEffect(() => {
const parser = new xml2js.Parser();
parser.parseString(inputData, function (err, result) {
setXmlData(result);
});
}, [inputData]);
console.log( xmlData && xmlData.email.body);
return (
<div>
Parse XML using ReactJs {xmlData && xmlData.email.body}
</div>
);
}
export default Parser;
I'm trying to build a website for displaying real-time charts in typescript with react for my learning. But I can not get values from a server properly before displaying the chart.
What I want to do is ...
Communication protocol is websocket using socket.io.
Using socket.io and storing data are inside React.Context(useSocket.tsx) so as to access the data from any react components easily.
Displaying the data is in Home.tsx.
The socket events are initial_data and new_data.
The initial_data event is received at the time the accessing the website at first.
The new_data event is received at regularly.
The time getting both events above, update values inside Home.tsx automatically.
I researched some articles on the web, for example, explaining a way that using socket.io inside a useEffect() function that returning socket.disconnect().
So, the code I built is below.
useSocket.tsx
import {useContext, createContext, useState, useEffect} from "react";
import {io, Socket} from "socket.io-client";
import {chartDataType} from "../types/chartDataType";
type Context = {
chartData: Array<chartDataType>;
}
const SocketContext = createContext<Context>({
chartData: [],
});
const SocketsProvider = (props: any) => {
const [chartData, setChartData] = useState();
useEffect( () => {
const socket: Socket = io("http://***.***.***.***");
socket.on('initial_data', (data) => {
console.log(data);
setChartData(data);
});
socket.on('new_data', (data) => {
console.log(data);
});
return () => { socket.disconnect() };
},[]);
return (
<SocketContext.Provider value={{chartData}} {...props} />
);
}
const useSocket = () => useContext(SocketContext);
export { SocketsProvider, useSocket };
Home.tsx
import {memo, VFC} from "react";
import { useSocket } from "../../context/useSocket";
import {Heading} from "#chakra-ui/react";
export const Home: VFC = memo(() => {
const { chartData } = useSocket();
return (
<>
<Heading as="h1">{`${chartData}`}</Heading>
</>
)
})
The above code caused an error Uncaught TypeError: Cannot read properties of undefined (reading '0') occurred in the browser console. But when the comment out the <Heading>...</Heading> line in Home.tsx, the console.log in useSocket.tsx can display the value from the server in the browser console.
I can not come up with the idea for the correct implementation. Is the definition of the type of the chartData wrong? or other reasons? The definition of the chartDataType has nothing wrong.
What is the way for the correct implementation?
What's happening is you are trying to render an empty array, the data hasn't loaded yet.
You need to check if charData exists, or if it's undefined first.
Like this:
return (
{CharData ? <Heading /> ... : null }
)
I hava a component called videoRow i try to render this component using dummy values now i get data from a useEffect Hook i have to use that data to render my component but when i try to do so it dont show anything. I even try console log to check weather i get my data or not it print my data on console means my useEffect is working But when i try this data on my videoRow component it not show anything
import React, { useState, useEffect } from "react";
import "../css/searchPage.css";
import TuneSharpIcon from "#mui/icons-material/TuneSharp";
import ChannelRow from "./ChannelRow";
import VideoRow from "./VideoRow";
import { selectInput } from "../features/inputSlice";
import { useSelector } from "react-redux";
import Axios from "axios";
function SearchPage() {
const getQuery = useSelector(selectInput);
const API_URL = `https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=4&key=APIKEY&type=video&q=${getQuery.input}`;
const [data, setData] = useState([]);
useEffect(() => {
async function fetchData() {
let request = await Axios.get(API_URL);
setData(request);
}
fetchData();
}, [API_URL]);
console.log(data);
return (
<div className="searchPage">
<div className="filter">
<TuneSharpIcon></TuneSharpIcon>
<h2>FILTERS</h2>
</div>
<hr></hr>
<ChannelRow
image="https://images.indianexpress.com/2022/01/Republic-Day_1200_AP2022.jpg"
channelName="Dummy"
verified
subs="670k"
noOfVideos={567}
desc="You can find awesome programming lessons here! Also, expect programming tips and tricks that will take your coding skills to the ..."
></ChannelRow>
<hr></hr>
{data?.data?.items?.forEach((item) => {
console.log(item.snippet.title);
console.log(item?.snippet.thumbnails.high.url)
console.log(item?.snippet.publishedAt)
console.log(item?.snippet.description)
console.log(item?.snippet.channelTitle)
return(<VideoRow
image={item?.snippet.thumbnails.high.url}
channelName={item?.channelTitle}
timestamp={item?.snippet.publishedAt}
title={item?.snippet.title}
desc={item?.snippet.description}
views="1.4M"
subs="1.4M"
></VideoRow>)
})}
</div>
);
}
export default SearchPage;
Change data?.data?.items?.forEach to data?.data?.items?.map. forEach returns nothing. So, even if you return the component from the callback, forEach will just ignore it. But, map will return all transformed results as an array.
You can read more about lists in react here.
I have read about React hooks and wanted to try it on this new website I have been developing. I am trying to pass an async function as a prop. Part of the function is to set my "cities" state and console log just to see if the API works. I have been receiving "setCities is not a function" error or, cities returns undefined if I just console log it directly. I think the function can't access the {cities, setCities} state. I have tried it in class component and it works. Has anyone encountered similar situations? Below is the code sample:
import React, { useState } from "react";
import axios from "axios";
import Menu from "./Menu";
function App() {
const { cities, setCities } = useState([]);
const searchSubmit = async term => {
try {
const res = await axios.get("http://localhost:8080/general/search", {
params: { city: term }
});
setCities(res.data);
console.log(cities);
} catch (err) {
console.log(err.message);
}
};
return (
<div className="ui container">
<Menu handleSearchSubmit={searchSubmit} />
</div>
);
}
useStates return an array, not an object...
So you can change
const { cities, setCities } = useState([]);
to
const [ cities, setCities ] = useState([]);
And it should work.