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;
Related
Guys I'm attempting to develop a modest film-based project. I have used TMDB Movies to obtain movies. I don't sure where I went wrong because the data in my console is displaying OK, but when I try to map and display that element, I receive an error saying "Movies.map is not a function." Please try to correct my mistake.
Thanks a lot!
enter image description here
`
import "./App.css";
import MemsData from "./Components/MemsData";
import NewMemsData from "./Components/NewMemsData";
import FilterElement from "./Components/FilterElement";
import MovieBox from "./Components/MovieBox";
import { useEffect, useState } from "react";
import Axios from "axios";
function App() {
const API_URL =
"https://api.themoviedb.org/3/movie/popular?api_key=8f11538792fbc26efa63aa919f0844b8";
const [movie, setMovie] = useState([]);
useEffect(() => {
Axios.get(API_URL).then((res) => {
console.log(res);
setMovie(res.data);
});
});
return (
<div className="App">
<h2>Movie Api</h2>
{
movie.map((moviereq, index) => {
return <div key={index}>{moviereq.title}</div>;
})}
</div>
);
}
export default App;
`
You need to go one deeper and access results: setMovie(res.data.results);
Codesandbox link: https://codesandbox.io/s/frosty-voice-hc912d?file=/src/App.js:392-400
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.
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 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>`}
/>
I am using a library in React called react-pdf which is having a component Document. Document Component contains a property called file (whose input type is a string).
How can I pass my response(props from redux) which is a base64 content, from the API into file property of Document?. So, Is there any library that accepts my base64 content from API and displays the output in a pdf document?
Here is the sample code :
import React from 'react';
import { connect } from 'react-redux';
import { Document } from 'react-pdf';
import { pdfData } from '../Store/ActionCreators'
class Billing extends React.Component {
componentDidMount() {
this.props.pdfData(mobile);
}
render() {
const { base64 } = this.props;
return (
<Document file=''>
</Document>
)
}
}
const mapStateToProps = state => ({
base64: state.login.data
})
export default connect(mapStateToProps, { pdfData })(Billing);
If I pass base64 to file then it is considering it as a string and outputting as base64.
Is there any relevant solution to work it out effectively?
Pdf-lib does support base64 by default and attached a sample to show how, and you need to know the pages numbers for your base64 document and to do that I used pdf-lib that I pass the base64 and get the attributes will be used to manipulate base64 document "rotating-scaling-merging-pdf-addImage-etc"
Sandbox Sample
const pdfDocument = await PDFDocument.load(base64);
const numPages = pdfDocument.getPageIndices();
Then pass the props and your data to as follow:
<Document file={`data:application/pdf;base64,${base64}`}>
{numPages.map((page, ind) => {
return <div key={ind} id={`viewer-page-${ind+1}`} className=" some-class-names">
<Page
key={`page_${ind + 1}`}
pageNumber={ind + 1}
scale={1} // you can scale by updating this
rotate={0} // you can scale by updating this
className={'some-class-names-page'}
width={400}
renderAnnotationLayer={false} // true by default
onRenderSuccess={renderMetricTracker}
/>
</div>;
})}
</Document>