How I handle the value array from Axios and fill the card
get the value from the array and show data
import React, { Component, Suspense } from "react";
import axios from "axios";
import {Card} from "reactstrap";
import { PHP } from "../../constants";
//api url adress server
const api = PHP;
const reqtoken = "Bearer " + localStorage.getItem("token");
class Property extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
load() {
axios
.get(api + "api/property", {
headers: {
"Content-type": "application/json",
Authorization: reqtoken
}
})
insert the data array on the state
.then(json => {
console.log show the data on console terminal
console.log(json.data.data.data);
this.setState({
data: json.data.data.data
});
})
.catch(erros => {
console.log(erros);
});
}
componentDidMount() {
this.load();
}
render() {
return (
<div>
map the array to handle the result................
{this.state.data.map(i => (
<Card>
<li>{i.address}</li>
</Card>
))}
</div>
);
}
}
export default Property;
didn't make me a wrong error console
I don't know how the response data comes in, but I found a problem with the code. You should pass keys.
{this.state.data.map(item => (
<Card key={item.id}>
<li>{item.address}</li>
</Card>
))}
https://reactjs.org/docs/lists-and-keys.html#keys
Related
I cannot figure out what I am doing wrong here. I submit a request to the API and an object is returned, but I cannot seem to get the component to render.
//Code
import React, { Component } from "react"
import axios from 'axios';
class Weather extends Component {
constructor(props){
super(props)
this.state = {
posts: [],
};
}
componentDidMount() {
const query = "Paris";
const apiKey = {api key here};
const unit = "metric";
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apiKey + "&units=" + unit;
axios.get(`${url}`)
.then(response => {
console.log(response);
this.setState({posts: response.data})
})
.catch(error => {
console.log(error);
})
}
render() {
const { posts } = this.state;
return(
<>
{posts.length ? <div>Temperature: {posts.main.temp} Description: {posts.weather[0].description}</div> : null}
</>
);
}
}
export default Weather;
enter image description here
[enter link description here][1]I am fetching API in react. I am able to see data in console but it is not appearing in JSX. I want to see Data id, name and value. But it is not appearing in browser.
[1]: https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js
import React from 'react';
import axios from 'axios'
import './App.css';
class Main extends React.Component {
constructor(props) {
super(props)
this.state = {
users: [],
error: ''
}
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/users')
.then( response => {
console.log(response);
this.setState({users: response.data})
})
.catch(error =>{
console.log(error);
})
}
render() {
const { users } = this.state
return (
<div>
<h2> Main Page</h2>
<p class="para-text"> Data from API</p>
{
users.length ?
users.map(post => <div key ={ users.id }> { users.name} </div>) : null
}
</div>
);
}
}
export default Main;
when mapping you named the key to your map as post and therefore when displaying them in jsx you must refer to that key
attached is a forked version of your sandbox https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js
import "./styles.css";
import React from "react";
import axios from "axios";
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
error: ""
};
}
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
}
render() {
const { users } = this.state;
return (
<div>
<h2> Main Page</h2>
<p class="para-text"> Data from API</p>
{users.length > 0
? users.map((post) => <div key={post.id}> {post.name} </div>)
: null}
</div>
);
}
}
export default Main;
I did fetch data from the NYTimes API and console log the response in the browser. I have done this by writing a function do_search. How can I send the responses as a prop to another component?
Here is a response form the API.
Here is my code for INDEX.JS. Please notice that I want to pass the prop in Listview component which is at 6th line from the last.
import React from "react";
import ReactDOM from "react-dom";
import SearchComponent from "./components/Search_component";
import ListViewComponent from "./components/Listview_component";
import _ from "lodash";
const axios = require("axios");
const api_key = "my_api_key";
let url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
q: " "
};
this.do_search("Bangladesh");
this.do_search = this.do_search.bind(this);
}
do_search(keyword) {
axios
.get(
url, // takes the variable url
{
params: {
api_key: api_key,
q: keyword
}
}
)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}
render() {
const search_throttle = _.debounce(keyword => {
this.do_search(keyword);
}, 500);
return (
<div>
<SearchComponent
searchkeyword={
search_throttle
}
/>
<ListViewComponent data={this.do_search.response.docs} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Assign the response to a state and pass this state as a prop.
this.state = {
q: " ",
searchResponse :null,
};
........
do_search = (keyword) =>{
axios
.get(...)
.then(function(response) {
console.log(response);
this.setState({searchResponse:response.data});
})
.........
<ListViewComponent data={this.state.searchResponse} />
</div>
Now when ever the state value gets its response from api, render is called again and listview gets the value.
Make an array where you will push response.data from then method in axios. Pass that array as prop to ListView component.
Inside ListView component make some loader that will show to the user that component is fetching data. When data arrives, show what you got from NYTimes API
Notice that when your state changes, views are re-rendered with props updated
import React from "react";
import ReactDOM from "react-dom";
import SearchComponent from "./components/Search_component";
import ListViewComponent from "./components/Listview_component";
import _ from "lodash";
const axios = require("axios");
const api_key = "9f4cd2e5a8884f3eb5853436e74be7e6";
let url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
q: " "
};
this.do_search("Bangladesh");
this.do_search = this.do_search.bind(this);
}
do_search(keyword) {
axios
.get(
url, // takes the variable url
{
params: {
api_key: api_key,
q: keyword
}
}
)
.then(function(response) {
console.log(response);
this.setState({ response }); // SET STATE HERE
})
.catch(function(error) {
console.log(error);
});
}
render() {
const search_throttle = _.debounce(keyword => {
this.do_search(keyword);
}, 500);
return (
<div>
<SearchComponent
searchkeyword={
search_throttle
}
/>
<ListViewComponent data={this.state.response} /> // GET STATE HERE
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
I im new in react js i have only 25 days of experience of reactjs and i am trying to fetch the data from url of embedly but i can not understand how to use it i am using the url which is ( https://api.github.com/users/hadley/orgs ) it is fetch the data correctly but i want to fetch the data from the embed.ly this is my page in react name is PostListItems.js
can any body help me thanks in advance.
Type isn't a field that is returned from Github's API.
import React from 'react';
import { render } from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch('https://api.github.com/users/hadley/orgs', {
method: 'GET',
})
.then((resp) => resp.json())
.then(data => {
this.setState({ data: data });
}).catch(error => {
console.log(error);
});
}
render() {
return <div>
{this.state.data.map((data, index) => {
return <div key={index}>{data.id}: {data.url}</div>
})}
</div>
}
}
render(<App />, document.getElementById('root'));
I am new to react-redux actually so I just need some help trying to understand any syntactical or logical mistake I am making here...
Basically, I want to display the reports fetched from another server. Function 'fetchNames' handles that and function 'fetchdownloadable' creates a returns a link that allows to pass through authentication and download the report in pdf onClick.
So I debugged on console, and I believe that there is something wrong with the order of execution of the code... when i debug.. i noticed that :
fetchnames is executed first to fetch all report data in json array...
then fetchDownloadable is called for each object in the reports array and that returns 'undefined' value on SampleChild...
then SampleChild is executed with undefined value...
and then we come back to execute the fetchDownloadable function that prints link value on the console and dispatches action on the reducer that returns the 'state' instead of 'action.reports_uri' in the reducer...
Thanks in advance!
SampleParent.js
import React, {Component} from 'react'
import { connect } from 'react-redux'
import { fetchNames, fetchDownloadable } from '../../actions/actions'
import SampleChild from '../ui/SampleChild'
class SampleParent extends Component {
constructor(props) {
super(props);
this.fetchDownloadLink = this.fetchDownloadLink.bind(this)
}
componentDidMount() {
const { dispatch } = this.props
dispatch(fetchNames())
}
fetchDownloadLink(uri){
this.props.dispatch(fetchDownloadable(uri))
}
render() {
return (<div><ul id="myUL">
{this.props.reports.map((report) => (
<li><SampleChild
key={report.id}
label={report.label}
uri={this.fetchDownloadLink("http://localhost:8080/sample"+report.uri+".pdf")}
/></li>))}
</ul></div>
)}
}
function mapStateToProps(state) {
const { reports } = state
return {
reports
}}
export default connect(mapStateToProps)(SampleParent)
SampleChild.js
import React, { Component } from 'react'
export default class SampleChild extends Component {
render() {
const { key, label, uri } = this.props
return (
<div className="inside_SampleChild" id={label}>
{label}
</img>
</div>
)}}
Action.js
import C from '../constants'
import fetch from 'isomorphic-fetch'
export const fetchNames = value => dispatch => {
var obj = { method: 'GET', headers: { 'Authorization': 'Basic ***', 'Accept': 'application/json' },
'credentials': 'include'};
fetch('http://localhost:8080/samplelink', obj)
.then(response => {
if (response.status !== 200) {
throw Error(response.status);
}return response;})
.then((response) => response.json())
.then(resourceLookup => {
var arr = [];
var length = resourceLookup.resourceLookup.length;
for(var i = 0 ; i< length ; i++){
arr.push(resourceLookup.resourceLookup[i]);}
dispatch({
type: C.FETCH_LIST_REPORTS,
reports: arr})}).
catch(error => {
console.log("There was this error" + error);});}
export const fetchReportDownloadable = (uri) => dispatch => {
var obj = {
method: 'GET',
headers: {
'Authorization': 'Basic ***=',
'Accept': 'application/json'
},
'credentials': 'include'
};
fetch(uri, obj)
.then(response => {
if (response.status !== 200) {
throw Error(response.status);
}
return response ;
})
.then((response) => response)
.then(resourceLookup => {
console.log(`resourceLookup URL: ${resourceLookup.url}`)
dispatch({
type: C.FETCH_DOWNLOADABLE,
report_uri: resourceLookup.url
})
}).
catch(error => {
console.log("There was this error" + error);
});}
Reducers.js
import C from '../constants'
import { combineReducers } from 'redux'
export const links = (state=null, action) =>
(action.type === C.FETCH_DOWNLOADABLE) ?
action.report_uri :
state
export const reports = (state=[], action) => {
switch(action.type) {
case C.FETCH_LIST_REPORTS :
return action.reports
default :
return state
}}
const rootReducer = combineReducers({
reports,
links
})
export default rootReducer
I will try explaining what is happening.
First, the first problem you have is that your passing a wrong value, or either undefined value of uri in:
<li>
<SampleChild key={report.id} label={report.label}
uri={this.fetchDownloadLink("http://localhost:8080/sample"+report.uri+".pdf")}
/>
</li>
Here uri is a function, that triggers on the first render, it dispatches the fetchDownloadable(uri) action, it does not return any value however. Hence the uri is undefined.
Secondly, you have C.FETCH_REPORT_DOWNLOADABLE constant used in your reducer. However you never dispatch an action of that type, the action dispatches C.FETCHING_DOWNLOADABLE. Hence the reducer does not do anything really, so the state does not change. My second comment was about C.FETCH_LIST_REPORTS, which is irrelevant for you right now, so I was wrong about that.
What I would do, is create the download link from the server side. Send it back with the report object. This way, you won't need to dispatch two actions to list your reports. Then, I will dispatch my action in componentWillMount(), once it's done fetching the data, the state will be changed - if, again, you have dispatched the correct action - and you will have your reports with the download URL in the same object.
Update
Okay I think that I understand now. What I would do then is to send the uri as string to SampleChild, and then when it mounts I will trigger the fetchDownloadablefunction.
SampleParent
import React, {Component} from 'react'
import { connect } from 'react-redux'
import { fetchNames, fetchReportDownloadable } from '../../actions/actions'
import SampleChild from '../ui/SampleChild'
class SampleParent extends Component {
constructor(props) {
super(props);
this.fetchDownloadLink = this.fetchDownloadLink.bind(this)
}
componentDidMount() {
const { dispatch } = this.props
dispatch(fetchNames())
}
fetchDownloadLink(uri){
this.props.dispatch(fetchReportDownloadable(uri))
}
render() {
return (<div><ul id="myUL">
{this.props.reports.map((report) => (
<li><SampleChild
key={report.id}
label={report.label}
uri={"http://localhost:8080/sample"+report.uri+".pdf"}
download={this.fetchDownloadLink}
/></li>))}
</ul></div>
)}
}
function mapStateToProps(state) {
const { reports } = state
return {
reports
}}
export default connect(mapStateToProps)(SampleParent)
SampleChild
import React, { Component } from 'react'
export default class SampleChild extends Component {
componentDidMount() {
this.props.download(this.props.uri);
}
render() {
const { key, label, uri } = this.props
return (
<div className="inside_SampleChild" id={label}>
{label}
</img>
</div>
)}}
What is supposed to happen now is that you will fetch the reports first in SampleParent then pass the information to SampleChild. Whenever a SampleChild is mounted, it will trigger fetchDownloadable action which in returns download the uri sent to it.