Is there anyway or example to make fetch and show data directly.
Say we have JSON data and we want to show once some data available so if there many objects in the JSON and once one data object is ready we show it and wait until next once and load once ready as well. We do this all in one endpoint.
Regards
What your describing is pretty standard in React.
Say you have your List component, and when the component mounts you watch to make a fetch to your API and render the data. You could do something like the below.
import React, {Component} from 'react'
export default class List extends Component {
state = {
listData: []
}
componentDidMount = () =>{
fetch('YOUR_URL_HERE')
.then(response => response.json())
.then(data => this.setState({ listData: data}));
}
render(){
return(
<div>
{this.state.listData.map((listItem, i)=>{
return <p>{listItem.propertyToRender}</p>
})}
</div>
)
}
}
Related
I need advice concerning redux-saga and the way to handle async call. I don't find anwsers to my questions.
I would like to know how can I handle properly async API call which return data used in only one component (so useless to store it in the store) ?
In my react application, I use redux-saga to handle async call. When the saga finish correctly, I dispatch a success action which store result in the store.
However, i find useless to store the result when I only want to display it in one component. Instead I would like to run a saga and return by a callback data to my component without storing it int the store. Is it possible ? How can I do that ?
thanks.
Here is a sample code for you, that code makes an api request in componentDidMount lifecycle and sets the data to its state and after it renders it.
import React, { Component } from "react";
import { render } from "react-dom";
import axios from 'axios';
class App extends Component {
constructor() {
super();
this.state = {
data: []
};
}
async componentDidMount() {
try {
let response = await axios.get('https://jsonplaceholder.typicode.com/users');
console.log('response.data: ', response.data);
this.setState({
data: response.data
});
} catch (error) {
console.log('error: ', error);
}
}
render() {
return (
<ul>
{this.state.data.map(item => <li>{item.name}</li>)}
</ul>
);
}
}
Hope this helps.
I have one fetch and one display .js file. However I am trying to figure out how to read the state. Of course as it's done now it's returned from the other .js file. But I would like to use the state that was set instead. How would I refactor to do this?
I would like to use the stateURL prop in the DataLoader.js
DataLoader.js
import React, { useState, useEffect } from 'react';
import useFetch from "./useFetch";
export default function DataLoader({stateURL}) {
const data = useFetch("/api");
// Should not be used
console.log("data", data);
const data2 = Object.keys(data).map(data => data);
console.log("data2", data2);
const data3 = data2.map(key => {
console.log("inside data3", key );
return data[key];
});
//This is empty
console.log("state", stateURL);
return (
<div>
<h1>Testing</h1>
<ul>
{Object.keys(data3).map(key => {
return <li>{data3[key].href}</li>;
})}
</ul>
</div>
);
}
useFetch.js
import { useState, useEffect } from "react";
export default function useFetch(url) {
const [stateURL, setStateURL] = useState([]);
console.log("url", url);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setStateURL(data._links));
}, []);
console.log("stateURL", stateURL);
return stateURL;
}
That is not possible. The hooks can only be referred from the original creating component.
Why do you just use the fetch hook within the display file?
If you want to keep these two components separated:
To access the data, you have to share the data somehow to be accessible to your other components. There are several ways to do it:
Pass the data up into the parent component via a callback and pass that into the other child component.
Using a state management library like Redux or Mobx.
Using the context API to share data between components but that might not be the best way for this kind of data.
It depends on your setup and your needs. If only these two components ever need that data, pushing it into the parent works fine.
If there are other components, which maybe need that data, you might want to use a state management lib.
Have a question about rendering fetched data with Axios. I’m able to log returned data to the console, however, it will not render on the screen.
I’m using an NPM Bitly module: https://www.npmjs.com/package/bitly
const BitlyClient = require('bitly');
const bitly = BitlyClient('ACCESS TOKEN');
State
class Example extends Component {
constructor() {
super();
this.state = {
landing: 'https://www.google.com/',
newUrl: 'https://www.udacity.com/'
};
API Call
componentDidMount() {
bitly.shorten(this.state.landing)
.then((response) => {
this.setState({newUrl: response.data.url })
console.log(response.data.url);
})
.catch(function(error) {
console.error(error);
});
}
This returns data to the console but does not render to the page.
Render to Page
<Component> {this.newUrl} </>
What am I missing?
It should be {this.state.newUrl}.
Literally started to work as soon as I posted this smh.
I just updated the component to include the state.
Did not work
<Component> {this.newUrl} </>
Does Work
<Component> {this.state.newUrl} </>
I'm trying myself in react and trying to make a simple application, which will display articles from the Hacker News. I have already made the first call to their API
componentDidMount() {
fetch('https://hacker-news.firebaseio.com/v0/jobstories.json?print=pretty')
.then(res => res.json())
.then(articles => {
this.setState({articles})
})
}
As the response, it returns an array of the articles IDs. To get detailed information for every single article I need to iterate the array I get and to make a second request for every article ID which has to look like
fetch(`https://hacker-news.firebaseio.com/v0/item/{id_from_the_array}`)
And I faced the problem because I have no idea how to implement it in a correct way.. Could someone please advice me?
this will help you
import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";
class App extends React.Component {
state = {
articles: []
};
componentDidMount() {
fetch("https://hacker-news.firebaseio.com/v0/jobstories.json?print=pretty")
.then(res => res.json())
.then(articles => {
articles.map(item => {
fetch(`https://hacker-news.firebaseio.com/v0/item/${item}.json?print=pretty`)
.then(res => res.json())
.then(detailArticles => {
const articles = this.state.articles.concat(detailArticles);
this.setState({ articles });
});
});
});
}
render() {
return <p>{JSON.stringify(this.state.articles) }</p>;
}
}
render(<App />, document.getElementById("root"));
codesandbox
One way you can do is like using pagenation or infinite scroll so you can show some 10 or 15 news on the screen and load the next set of data on click of a button. Else you can show only id's on screen and fetch the data on click of a button.
I'm completely new to React and having a hard time understanding it.
I've been tasked with creating a really simple API fetch to an OData endpoint.
Now, I've come across this library https://www.npmjs.com/package/react-odata
Which looks fantastic! However I just do not understand how to even get something like this working.
I understand the very basic principles of how react works and have gone through many basic tutorials. But for whatever reason I can not get my head around this one.
So how could I use this library to simply query an OData endpoint and display the raw data?
So the issue with this, is that I didn't understand that I still have to explicitly make the call and return the data from that.
import React, { Component } from 'react';
import Fetch from 'react-fetch-component';
import OData from 'react-odata';
const baseUrl = 'http://services.odata.org/V4/TripPinService/People';
const query = { filter: { FirstName: 'Russell' } };
export default class App extends Component {
render() {
return (
<div>
<h1>Basic</h1>
<OData baseUrl={baseUrl} query={query}>
{({ loading, data, error }) => (
<div>
{loading && <span>Loading... (()=>{console.log(loading)}) </span>}
{data && data.value.map((d, i) => <div key={i} id={i}>{d.FirstName}</div>)}
</div>
)}
</OData>
</div>
);
}
/* Setup consistent fetch responses */
componentWillMount() {
fetch('http://services.odata.org/V4/TripPinService/People')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.value[0].FirstName
})
.catch((error) => {console.error(error)});
}
}
from the given link in the question I found that this component used the react-fetch-component as a base to make the call.
It seems that the package you linked would expose a React component that you would use to wrap your own components so you would have access to the fetched data and could pass it down as properties. At least that is what I understand from its README.
I imagine it would be something like this:
<OData baseUrl={baseUrl} query={query}>
{ ({ loading, error, data }) => (
<div>
<YourComponent data={data} />
</div>
)}
</OData>
This would be using react-odata, but you don't need that package to do what you want. You could just do a regular AJAX call on the URL and feed your components with the returned data.
This post may help: http://andrewhfarmer.com/react-ajax-best-practices/