score:0
My React component is using FetchAPI and has two return statements.
No, it doesn't. It has one:
render() {
let theList = this.state.map((item, id) => {
return (
<Card>A bunch of API Stuff </Card>
);
})
return ( // <========== here
<div className="search-wrap">
<Row>
{theList}
</Row>
</div>
)
}
The other one is a return
within your map
callback, which doesn't have any effect on your render
method at all.
If you want to use the conditional operator to show a loading indicator, you'd do it in your render
's return:
render() {
let { loading } = this.state; // *** Get the flag
let theList = this.state.map((item, id) => {
return (
<Card>A bunch of API Stuff </Card>
);
})
return ( // *** Use it in the below
<div className="search-wrap">
<Row>
{loading ? <p>Loading...</p> : theList}
</Row>
</div>
)
}
You might also want to avoid the unnecessary map
call, but if you know your state is initialized with an empty array, that call is harmless. But if you want to get rid of it:
render() {
let { loading } = this.state; // *** Get the flag
let theList = !loading && this.state.map((item, id) => {
return (
<Card>A bunch of API Stuff </Card>
);
})
return ( // *** Use it in the below
<div className="search-wrap">
<Row>
{loading ? <p>Loading...</p> : theList}
</Row>
</div>
)
}
score:0
Just add a boolean field to your state which indicates that data is being loaded.
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading: true, // this one
};
}
componentDidMount() {
fetch('https.data.json')
.then(response => response.json())
.then(data => this.setState({ data: data, loading: false }))
}
render() {
if (this.state.loading)
return <div>Loading...</div>
let theList = this.state.map((item, id) => {
return (
<Card>A bunch of API Stuff </Card>
);
})
return (
<div className="search-wrap">
<Row>
{theList}
</Row>
</div>
)
}
}
export default App;
score:0
If I understand correctly, your code should look like the following:
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: false
};
}
componentDidMount() {
this.setState({ isLoading: true }); // mount the loading component when we will start the fecth
fetch('https.data.json')
.then(response => response.json())
.then(data => this.setState({ data: data}))
.then(() => this.setState({ isLoading: false })) // unmount Loading component when the fetch ends
}
render() {
let theList = this.state.map((item, id) => {
return (
<Card>A bunch of API Stuff </Card>
);
})
// Here we will return the Loading component as long as isLoading is true
return (isLoading) ? <Loading /> : (
<div className="search-wrap">
<Row>
{theList}
</Row>
</div>
)
}
}
export default App;
So basically we will add a boolean variable (isLoading) that will handle the state of the fetch and we will add it into the state of the component. When the fetch is triggered, this variable will be true
otherwise it will be false
.
So then in the return
statement, we can use a ternary operator based on the value of this new variable. If it is true
we will return a Loading component or a simple div
saying Loading...
. Otherwise we will return the App component with the data loaded.
I hope this help :)
score:0
You can do something like this. Note that you can export directly the class since the beginning. Also, you can simplify the state, without a explicit constructor.
To know the fetch state, you should add a isLoading
condition before and after fetching the data. Then, in the render, you can return one single node, and inside render the components that you want based on your status. With this coding style, you can even show when the fetch returns an empty array.
export default class App extends Component {
state = {
data: [],
isLoading: false
}
componentDidMount() {
this.setState({
isLoading: true
}, () => {
fetch('https.data.json')
.then(response => response.json())
.then(data => this.setState({
data,false
}))
})
}
render() {
return (
<div>
{
this.state.isLoading &&
<span>
Loading...
</span>
}
{
!this.state.isLoading &&
(this.state.data.length > 0) &&
<div className="search-wrap">
<Row>
{
this.state.data.map((item, id) => {
return (
<Card key={id}>
A bunch of API Stuff
</Card>
);
})
}
</Row>
</div>
}
{
!this.state.isLoading &&
(this.state.data.length === 0) &&
<span>
There's no data to show
</span>
}
</div>
)
}
}
Hope this helps! Denny
Source: stackoverflow.com
Related Query
- How to set Ternary Operator "Loading" Div inside React Component with Two Return statements?
- How to 1). put a div , 2). render a component without Route inside <Routes> with React Router in v6 React?
- How to use ternary operator within the jsx of a react component along with typescript?
- React Router v6 : How to render multiple component inside and outside a div with the same path
- How to ensure a constant inside a component is only calculated once on start in React (Native) with hooks?
- How to put a div inside a Switch with React Router?
- How to prevent component re-render (update) inside animations with REACT
- How to have two function calls inside ternary operator in JSX?
- How to test a React component that has Router, Redux and two HOCs... with Jest and Enzyme?
- React How to return div and variable value for another component
- Ternary operator fails when used to set value of datalist option in React component
- How to set two properties for a React component as optional depending on another property using TypeScript?
- How do I fix a React TypeScript error with the return value of useHotkeys hook not matching the type of the div element ref prop
- How to set a loading state for react component while sorting and filtering data?
- How to test a function inside React functional component using jest.spyOn with React Testing Library
- How set displayName to a React stateless component with memo?
- How to get http header(LDAP user attribute set by Nginx) with React component
- React ternary operator with array.map return
- How to link to Routes inside the component rendered by another Route with React Router
- React - How do I include a dynamic variable with ternary operator
- How do I check if the imported component in my return exists in the document with React Testing Library?
- How to set state inside a loop with a time delay in react js
- How to use Font Awesome Icons with Text using ternary operator in React JS?
- React - How to return a component with a dynamic name?
- How to create React component with components inside it?
- How to use ternary operator using react with route?
- How to add a ternary operator in css in js with react spring
- How can I do a ternary operator inside a map with the mapping for the true condition but without the mapping for the false
- How can i can change the value of a variable with if/else to return certain div in react
- How to set state of a react component with a specific item from a returned json object?
More Query from same tag
- ReactJS Get Call Returns Entire Array But Not Single Index
- How do I create a new JSON object inside a react hook?
- React Star Rating Component
- How to use css modules with create-react-app?
- How to create MUI Dialog with transparent background color?
- Trigger a function at particular time everyday in javascript
- how to undo transform using onMouseLeave React
- How can we use react jsx templates in node-webkit
- Convert nested JSON Arrays to Chart.js input
- How can I set enabled to a button only If the user types in numbers in the input?
- How to do animations with React and Immutable.js?
- TS2339: Property X does not exist on type '{}'
- Unable to find only Button Component for test
- Rendering react components inside popup of react-leaflet-draw drawn layer on react-leaflet
- How to write right regular expression for my Route path in React JS
- How do you style a component to be under another component?
- React event delegation from parent to child
- How can one prevent excess JS event handlers in React?
- Can not remove my Gutenberg block. It has been fixed on editor page
- How can I get my input to render in a paragraph, using React?
- Dynamically add more screens to stackNavigator on react navigation
- TypeError: ReactHtmlParser is not a function
- Wait for Completion in reactjs
- Controlled React components in Reagent
- Getting TS Error: Property 'user' does not exist on type 'IAuth | null'
- How to set values in a multi-step Formik form with components that implement useField()
- How to add icons and tooltip on react-select component?
- Trying to use Bootstrap Nav Pills in React Router's NavLink
- IIS two sites using same url, ReactJS front, ASP Net Core backend, can't reach backend
- Is there a clean way to serve React builds from a Rust Rocket backend