Return xml json data in react component - javascript

I am builing my first app in React. I have data in XML file using xml2js converting them to json object abd then i am trying to return title every single AD but without success. I think that may be a problem with this part .then(data => this.setState({postsList: [data]})?
import React, {Component} from 'react';
import {parseString} from 'xml2js'
class AdListing extends Component {
state = {
postsList: [],
};
componentDidMount() {
fetch('export.xml')
.then(response => response.text())
.then(responseText => {
parseString(responseText, function (err, data) {
console.log(data) [1]
return data
})
})
.then(data => this.setState({
postsList: [data]
}));
};
renderList = () => this.state.postsList.map((item, id) => <div>>{item.JOB_TITLE}></div>);
render(){
return(
<div>
<p>oleole</p>
{this.renderList()}
</div>
)
}
}
export default AdListing;
[1] Array looks like: https://i.stack.imgur.com/xQUB0.png

Related

Can't access prop in another component?

I'm getting myself confused with React here (total newbie). I have a simple component that fetches some data that always returns {"score":100}:
import React, { useEffect, useState } from "react";
import Graph from "./Graph.js";
const UsingFetch = () => {
const [results, setResults] = useState({"score": null}); // initially set score to null
const fetchData = () => {
fetch("https://myapi.com/id=1")
.then((response) => {
return response.json();
})
.then((data) => {
setResults(data); // update results with integer score
});
};
useEffect(() => {
fetchData();
}, []);
console.log(results)
return (
<div>
<Graph results={results.score}></Graph>
</div>
);
};
export default UsingFetch;
My Graph.js looks like the following:
import { React } from 'react'
export default function Graph({results}) {
console.log(results)
return (
<div>
<h1>{results}</h1>
</div>
)
}
Why doesn't the score render on the page? I've confirmed that the data returns correctly, I just can't seem to access it right.
Here's the console output:
Results is an array.
<h1>{results.map((result) => (result.score)}</h1>

multiple API calls in one componentDidMount using Axios in react

Here is my React js code for a single API call for a date range picker. now I want to call multiple API in React with componentDidMount Method is it possible if yes how can do that
import React,{ Component} from "react";
import axios from 'axios'
class PostList extends Component{
constructor(props) {
super(props)
this.state = {
posts: []
}
}
componentDidMount(){
axios.get('http://127.0.0.1:8000/betweendays')
.then(response => {
this.setState({
posts:response.data
})
console.log(response.data)
})
}
render() {
const {posts} = this.state
return (
<div>
<h1>get call in React js</h1>
{
posts.map(post => <div key = {post.id}>{post.id} </div>)
}
</div>
)
}
}
export default PostList```
Using .then() method to create chain of the requests..
componentDidMount() {
axios.get('http://127.0.0.1:8000/betweendays')
.then(response => {
this.setState({
posts: response.data
})
return response.data; // returning response
})
.then(res => {
// do another request Note we have the result from the above
// getting response returned before
console.log(res);
})
// Tag on .then here
.catch(error => console.log(error))
}
You can add more apis in componentDidMount as u want.
componentDidMount(){
axios.get('http://127.0.0.1:8000/betweendays')
.then(response => {
this.setState({
posts:response.data
})
console.log(response.data)
})
axios.get('link')
.then(response => {
this.setState({
posts:response.data
})
console.log(response.data)
})
}

How to take the result from a fetch request and insert data into jsx?

I am trying to manipulate the request from an api call and insert info into my jsx, but I get this error:
"Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead."
I can see that it has something to do with this my jsx includes a promise, but I dont understand why.
import React from "react";
export default function Card_Container() {
return (
<div>
{fetch("http://localhost:1337/posts")
.then((res) => res.json())
.then((data) => {
data.map((post) => {
return <h1>{post.blogtitle}</h1>;
});
})}
</div>
);
}
As the error report, the jsx file can't render a object promise, try to do something like this:
import React, { useEffect, useState } from "react";
export default function Card_Container() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("http://localhost:1337/posts")
.then((res) => res.json())
.then((res) => {
setData(res);
});
}, []);
return (
<div>
{data.map((post) => {
return <h1>{post.blogtitle}</h1>;
})}
</div>
);
}
The useEffect is triggered once the component has been mounted, when the fetch call receive a response from the server the setState will store the information into data and the component will be rendered again, but this time if the response is correctly stored into data you should see a list of h1 in your application
Import React from "react";
export default function Card_Container() {
return (
<div>
{ fetch("http://localhost:1337/posts")
.then((res) => res.json())
.then((data) => {
data.map((post => {
<h1>{post.blogtitle}</h1>
))})};
</div>
);
}
The problem is not with the logic but syntax. => already works as a return so no need to add another.
Best Practice:
componentDidMount(){
console.log(">>>>> componentDidMount...");
url= 'http://localhost:1337/posts';
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
console.log(JSON.stringify(responseJson));
this.setState({result:responseJson});
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
render() {
return(
<div>
{this.state.result.map(post => (
<h1>{post.blogtitle}</h1></div>))}

How do I access json using reactjs from expressjs?

I am new to reactjs and expressjs. How do I get the data from reactjs and store it in a variable.
So far I am able to do res.send the data.
app.get('*', (req, res) => {
const data = {hello: world};
res.send(data);
});
This sends the data to the browser and displays but I want to just save the data to a variable instead of displaying it.
This is React.js example
import axios from 'axios'
click () {
axios.get('yourAPIAdress')
.then(response => console.log(response))
}
and this is your node.js example code;
const https = require('https');
https.get('yourAPIAdress', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
You can in your React Component do something like:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(){
super();
this.state ={users: []};
}
componentDidMount() {
fetch('/users')
.then(users => {
console.log(users);
this.setState({ users })
});
}
render() {
return (
<div className="App">
<h1>Users</h1>
{this.state.users.map(user =>
<div key={user.id}>user: {user.name} Password: {user.password}</div>
)}
</div>
);
}
}
export default App;
Assuming the object you're interested in called "users"
(* You need to change your JSX according to your object fields for sure, to test this)

How to display data from Rails 5 API in React.js frontend app?

I have set up an API with Rails, with a http://localhost:3001/api/words endpoint exposing the following data:
[{"id":1,"term":"Reach","definition":"Reach is the number of people who had any content from your Page or about your Page enter their screen.","example":"","author":"Loomly","credit":"https://www.loomly.com/","created_at":"2018-11-02T03:21:20.718Z","updated_at":"2018-11-02T03:21:20.718Z"},{"id":2,"term":"Emoji","definition":"A small digital image or icon used to express an idea, emotion, etc., in electronic communication","example":"","author":"Loomly","credit":"https://www.loomly.com/","created_at":"2018-11-02T03:23:50.595Z","updated_at":"2018-11-02T03:23:50.595Z"}]
I am now trying to simply display this data (ideally as an unordered list) in a React.js frontend application built with Create React App, and here is the content of my App.js file:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor () {
super()
this.state = {}
this.getWords = this.getWords.bind(this)
this.getWord = this.getWord.bind(this)
}
componentDidMount () {
this.getWords()
}
fetch (endpoint) {
return window.fetch(endpoint)
.then(response => response.json())
.catch(error => console.log(error))
}
getWords () {
this.fetch('/api/words')
.then(words => {
if (words.length) {
this.setState({words: words})
this.getWord(words[0].id)
} else {
this.setState({words: []})
}
})
}
getWord (id) {
this.fetch(`/api/words/${id}`)
.then(word => this.setState({word: word}))
}
render () {
let {words, word} = this.state
return (
<div>
{Object.keys(words).map((key) => {
return (
<div key={word.id}>
<p>{word.term}</p>;
</div>
)
})}
</div>
)
}
}
export default App;
I believe the problem is located in the following area of the code:
render () {
let {words, word} = this.state
return (
<div>
{Object.keys(words).map((key) => {
return (
<div key={word.id}>
<p>{word.term}</p>;
</div>
)
})}
</div>
)
}
I have tried to follow the steps explained in this tutorial, as well as in that other tutorial, while keeping the layout of the page as simple as possible (no bells & whistles from semantic-ui-css), and no matter what I try, I keep getting into of the following errors:
TypeError: Cannot convert undefined or null to object
Unexpected token, expected “,”
Failed to compile: 'word' is not defined no-undef
The solution explained in this article led me to the code I have now, but there is something I am missing about the way to structure my React app: can you point me in the right direction?
getWords () {
fetch('http://localhost:3001/api/words')
.then((response) => {
return response.json();
})
.then((res) => {
// console.log(res); you should get the response you mentioned
this.setState({words: res});
});
}
Then check Are you getting data in your state by consoling it.
Then you can work on it using following
render{
return(
<div>
{ this.state.words.map((val) => (
<span>{val.term}</span>
))}
</div>
)
}
The problem is here: let {words, word} = this.state;
this.state doesnt have word property yet. You could initialize this.state like this:
this.state = {
words: [],
word: {}
};
be free to ask
There are two issues with the code in the question:
words & word are not defined.
Iteration through words in the render() function was not set properly with keys.
Thanks to the answers and comments left on this question, here is the code I ended up using:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor () {
super()
this.state = {
words : [],
word : {}
}
this.getWords = this.getWords.bind(this)
this.getWord = this.getWord.bind(this)
}
componentDidMount () {
this.getWords()
}
fetch (endpoint) {
return window.fetch(endpoint)
.then(response => response.json())
.catch(error => console.log(error))
}
getWords () {
this.fetch('/api/words')
.then(words => {
if (words.length) {
this.setState({words: words})
this.getWord(words[0].id)
} else {
this.setState({words: []})
}
})
}
getWord (id) {
this.fetch(`/api/words/${id}`)
.then(word => this.setState({word: word}))
}
render () {
let {words} = this.state
return (
<ul className="words-container">
{Object.keys(words).map((key) => {
return (
<li className="word-container" key={key}>
{words[key].term}: {words[key].definition}.
</li>
)
})}
</ul>
)
}
}
export default App;

Categories