Handling http error in react for path not found - reactjs

I am trying to handle the HTTP error in my application for the unknown path using catch and by changing the state of the application. I am changing the state of the application to display the details of the unknown path but it's not working. Can anyone suggest me how to do that? I have added my code below
App.js
import React, { Component } from 'react'
import charactersFile from "./data/characters.json"
import axios from 'axios';
import './App.css';
class App extends Component {
state = {
movies: [],
loading: true,
error: ''
};
handleClick = character => {
console.log(character.name);
const PeopleUrl = `https://swapi.co/api/people/`;
const FilmUrl = `https://swapi.co/api/films/`;
switch (character.name) {
case "Luke Skywalker":
axios
.get(`${PeopleUrl}1/`)
.then(response =>
Promise.all([
axios.get(`${FilmUrl}2/`),
axios.get(`${FilmUrl}6/`),
axios.get(`${FilmUrl}3/`),
axios.get(`${FilmUrl}1/`),
axios.get(`${FilmUrl}7/`)
])
)
.then(result =>
result.map(values =>
this.setState({
movies: [
...this.state.movies,
{
title: values.data.title,
release_date: values.data.release_date
}
],
loading: false,
render: true
})
)
);
break;
case "C-3PO":
axios
.get(`${PeopleUrl}2/`)
.then(response =>
Promise.all([
axios.get(`${FilmUrl}2/`),
axios.get(`${FilmUrl}5/`),
axios.get(`${FilmUrl}4/`),
axios.get(`${FilmUrl}6/`),
axios.get(`${FilmUrl}3/`),
axios.get(`${FilmUrl}1/`)
])
)
.then(result =>
result.map(values =>
this.setState({
movies: [
...this.state.movies,
{
title: values.data.title,
release_date: values.data.release_date
}
],
loading: false,
render: true
})
)
);
break;
case "Leia Organa":
axios.get(`${PeopleUrl}unknown/`)
.then(response => {
if (response.status === 404) {
this.setState({ error: "Details not found" })
}
}).catch(error => {
console.log(error); // They are other network errors
this.setState({ error: 'Network error' })
})
break;
case "R2-D2":
axios
.get(`${PeopleUrl}3/`)
.then(response =>
Promise.all([
axios.get(`${FilmUrl}2/`),
axios.get(`${FilmUrl}5/`),
axios.get(`${FilmUrl}4/`),
axios.get(`${FilmUrl}6/`),
axios.get(`${FilmUrl}3/`),
axios.get(`${FilmUrl}1/`),
axios.get(`${FilmUrl}7/`)
])
)
.then(result =>
result.map(values =>
this.setState({
movies: [
...this.state.movies,
{
title: values.data.title,
release_date: values.data.release_date
}
],
loading: false,
render: true
})
)
);
break;
default:
return "No list item";
}
};
render() {
console.log(this.state);
const Content = this.state.loading ? (
<div style={{ marginTop: "20px", padding: "20px" }}>"Loading..."</div>
) : (
<ul>
{this.state.movies.map(movie => (
<li key={movie.title}>
{movie.title} - {movie.release_date}
</li>
))}
</ul>
);
const List = (
<ul>
{charactersFile.characters.map(character => {
return (
<li
key={character.name}
onClick={() => this.handleClick(character)}
>
{character.name}
</li>
);
})}
</ul>
);
return <div className="App">{!this.state.render ? List : Content}</div>;
}
}
export default App;
characters.json
{
"characters": [
{
"name": "Luke Skywalker",
"url": "https://swapi.co/api/people/1/"
},
{
"name": "C-3PO",
"url": "https://swapi.co/api/people/2/"
},
{
"name": "Leia Organa",
"url": "https://swapi.co/api/people/unknown/"
},
{
"name": "R2-D2",
"url": "https://swapi.co/api/people/3/"
}
]
}

The problem is
You don't set loading to false when error occurs.
You don't check for errors in your render method.
First lets extract the presentation components to small function components to make the main component more simple
const Error = ({ message }) => <h3>{message}</h3>;
const Loader = () => (
<div style={{ marginTop: "20px", padding: "20px" }}>"Loading..."</div>
);
const List = ({ handleClick }) => (
<ul>
{charactersFile.characters.map(character => {
return (
<li key={character.name} onClick={() => handleClick(character)}>
{character.name}
</li>
);
})}
</ul>
);
const Content = ({ movies }) => (
<ul>
{movies.map(movie => (
<li key={movie.title}>
{movie.title} - {movie.release_date}
</li>
))}
</ul>
);
App
class App extends Component {
state = {
movies: [],
loading: false,
error: ""
};
handleClick = character => {
// Set loading to true and error to false
this.setState({ loading: true, error: false, movies: [] });
console.log(character.name);
axios
.get(character.url)
.then(({ data }) =>
Promise.all(data.films.map(filmUrl => axios.get(filmUrl)))
)
.then(result => {
const movies = result.map(({ data: { title, release_date } }) => ({
title,
release_date
}));
this.setState({ movies, loading: false, error: "" });
})
.catch(() => {
this.setState({
movies: [],
loading: false,
error: "List not found"
});
});
};
render() {
const { error, loading, movies } = this.state;
return (
<div className="App">
{/* include Content component only when there is data */}
{movies.length > 0 ? (
<Content movies={movies} />
) : (
<List handleClick={this.handleClick} />
)}
{/* include Loader component when loading */}
{loading && <Loader />}
{/* include Error component when there is an error */}
{error && <Error message={error} />}
</div>
);
}
}
If you have any questions about the code let me know.
Working sandbox

404 error was judged not by catch but by normal request.
So you can catch 404 like .then(res => {if(res.status === 404)} or .then(res => { if(!res.ok) })
Some example for your code
axios.get(`${PeopleUrl}unknown/`)
.then(response => {
if(response.ok) {
console.log(response.data);
} else {
console.log('Details not found.'); // It is 404 error
this.setState({ error : 'Details not found' });
}
})
.catch(error => {
console.log(error); // They are other network errors
this.setState({ error : 'Network error' })
})

Related

Undefined values React

I'm trying to achieve making a suspend user button via updating the values of the user the status to Suspended, but the problem is the status is defined but other values are undefined did I do something wrong or is there any way to update the values to make the other variable like a name not required?
This is what I mean:
This is my code:
const User = (props) => (
<>
<DropdownButton id="dropdown-basic-button" title="Action">
<Dropdown.Item>
<a
href="user"
onClick={() => {
props.onSubmit(props.user[0]);
}}
>
<i className="fas fa-trash"></i> Suspend
</a>
</Dropdown.Item>
</DropdownButton>
</>
);
export default class Users extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
this.state = { users: [] };
}
componentDidMount() {
axios
.get("http://localhost:5000/users/")
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
}
onSubmit(id) {
const user = {
name: this.state.name,
password: this.state.password,
email: this.state.email,
storeName: this.state.storeName,
storeUrl: this.state.storeUrl,
date: this.state.date,
status: "Suspended",
};
console.log(user);
axios
.post("http://localhost:5000/users/update/" + id, user)
.then((res) => console.log(res.data));
}
userList(currentuser) {
return (
<User
user={currentuser}
key={currentuser[0]}
onSubmit={this.onSubmit}
/>
);
}
render() {
const columns = [
{
name: "_id",
options: {
display: false,
},
},
{
name: "name",
label: "Name",
options: {
filter: true,
sort: true,
},
},
{
name: "Action",
options: {
customBodyRender: (value, tableMeta, updateValue) => {
return <>{this.userList(tableMeta.rowData)}</>;
},
},
},
];
const { users } = this.state;
return (
<>
<MUIDataTable data={users} columns={columns} />
</>
);
}
}
You didn't define nor set the User's individual attributes' values in the state! So, no wonder they show up as undefined, when you try to read them...
The simplest solution would be:
onSubmit(id) {
//let user = this.state.users.find(user => user.id === id); // find by id
let user = this.state.users[id]; // find by index
if (user) {
user.status = 'Suspended';
console.log(user);
axios
.post("http://localhost:5000/users/update/" + id, user)
.then((res) => console.log(res.data));
}
}

Re render component React table

I am trying to re render a component. I have a refresh button and I want to clean all filters and sorting values when clicked.
The thing is that I can not make a re render, not even with forceUpdate(), it is doing NOTHING and I don't know why. Also, I tried with setState(), and nothing. What I want to happen is what happens when I change the page, it re renders the component. Please can anybody could help me? What am I doing wrong?
import React, { Component } from "react";
import DeleteComponent from "../components/DeleteComponent"
import ReactTable from 'react-table';
import { Link, withRouter } from 'react-router-dom';
import axios from "axios";
import { getJwt } from '../helpers/jwt'
import eye from '../img/eye.png'
import bin from '../img/bin.png'
import writing from '../img/writing.png'
class CustomReactTable extends Component {
constructor(props) {
super(props)
this.state = {
data: [],
showDelete: false,
item: null,
pages: null,
totalItems: null,
loading: false,
state: {},
}
}
fetchData = (state) => {
this.setState({ state: state })
const jwt = getJwt()
if (!jwt) {
this.props.history.push('/login')
}
let config = {
headers: { 'Authorization': `Bearer ${jwt}` },
params: {
page: state.page,
pageSize: state.pageSize,
sorted: state.sorted,
filtered: state.filtered
}
}
this.setState({ loading: true })
axios.get(`http://localhost:3001/api/v1${this.props.location.pathname}`, config)
.then(response => {
console.log(response)
this.setState({
data: response.data.result,
loading: false
})
})
axios.get(`http://localhost:3001/api/v1${this.props.location.pathname}/count-documents`, config)
.then(response => {
this.setState({
totalItems: response.data.result,
pages: Math.ceil(response.data.result / state.pageSize)
})
})
}
loadOptions = () => {
this.props.columns.push({
Header: "",
Cell: (row) => [
// Find a better way to add unique key
<Link to={`${this.props.location.pathname}/${row.original._id}/show`} key={row.original._id} params={{ id: row.original._id }}><button className="btn-xs btn-outline-light"><img style={{ width: '1em' }} src={eye} /></button></Link>,
<Link to={`${this.props.location.pathname}/${row.original._id}/edit`} key={row.original._id + 'a'}><button className="btn-xs btn-outline-light"><img style={{ width: '1em' }} src={writing} /></button></Link>,
<button key={row.original._id + 'b'} className="btn-xs btn-outline-light" onClick={() => { this.onClickDeleteButton(row.original._id) }}><img style={{ width: '1em' }} src={bin} /></button>
]
})
}
loadFunctionalities = () => {
return (
<div className='functionalities-react-table'>
<span className='functionalities-add-item-table'>
<Link to={`${this.props.location.pathname}/add`}><button className="btn-sm btn-outline-success">Add new {this.props.modelName}</button></Link>
</span>
<span className='functionalities-refresh-table'>
<button className="btn-sm btn-outline-dark">Refresh table</button>
</span>
</div>
)
}
onClickDeleteButton = (id) => {
this.setState({ showDelete: true, item: id })
}
onCancelDeleteClick = () => {
this.setState({ showDelete: false })
}
componentDidMount() {
this.loadOptions()
}
reloadData = () => {
this.fetchData(this.state.state)
}
render() {
return (
<div className='main-content'>
{this.state.showDelete && (
<DeleteComponent reloadData={this.reloadData} onCancelDeleteClick={this.onCancelDeleteClick} item={this.state.item} />
)}
<h3>{`${this.props.modelName} (${this.state.totalItems})`}</h3>
{this.loadFunctionalities()}
<ReactTable
data={this.state.data}
columns={this.props.columns}
manual
onFetchData={this.fetchData}
defaultPageSize={10}
pages={this.state.pages}
style={{ fontSize: '0.9em' }}
>
</ReactTable>
<div className="total-records-tag">{this.props.modelName}: {this.state.totalItems}</div>
</div >
)
}
}
export default withRouter(CustomReactTable);

React TypeError: this.state.entries.map is not a function

My React app works on my computer but when I deploy to Heroku I'm getting an error that states " TypeError: this.state.entries.map is not a function" under console in google chrome tools and the page won't load. I'm not sure why. Can anyone help me with this issue? Below is the code from that page.
class Journal extends Component {
state = {
entries: [{}],
date: "",
title: String,
entry: String,
cdate: "",
ctitle: String,
centry: String,
searchbar: true,
show: false
}
componentDidMount() {
this.loadEntries();
}
loadEntries = () => {
API.getEntries()
.then(res => {
console.log(res.data)
this.setState({ entries: res.data, title: "", date: "", entry: "" })
})
.catch(err => console.log(err));
};
displaySearchBar = () => {
this.setState({ searchbar: false }, () => { console.log("Search bar") })
}
showModal = (currentEntry) => {
console.log(currentEntry, "Show Modal");
this.setState({
show: true,
centry: currentEntry.entry,
ctitle: currentEntry.title,
});
};
hideModal = () => {
this.setState({ show: false });
};
render() {
return (
<Container fluid>
<br />
<Row>
<Col size="md-2" />
<>
<Col size="md-8">
<div className="card mb-3">
<h1>Journal Entries</h1>
{this.state.entries.length ? (
<List>
{this.state.entries.map(entry => (
<ListItemDetail
key={entry.id}
showModal={this.showModal}
title={entry.title}
date={entry.date}
entry={entry.entry}
id={entry.id}
loadEntries={this.loadEntries}>
</ListItemDetail>
))}
</List>
) :
(<h3>No Results to Display</h3>)
}
your code should be like this.
loadEntries = () => {
API.getEntries()
.then(res => {
console.log(res.data)
this.setState({ entries: [res.data], title: "", date: "", entry: "" })
})
.catch(err => console.log(err));
};
It seems your entries is not receiving an array, that's why you are getting this problem.

Reactjs: How to properly fetch each users record from database on pop button click using Reactjs

The code below shows each user info on users list button click.
Now I want fetch each users record from database on users list button click.
In the open() function, I have implemented the code below
open = (id,name) => {
alert(id);
alert(name);
//start axios api call
const user_data = {
uid: 'id',
uname: 'name'
};
this.setState({ loading_image: true }, () => {
axios.post("http://localhost/data.php", { user_data })
.then(response => {
this.setState({
chatData1: response.data[0].id,
chatData: response.data,
loading_image: false
});
console.log(this.state.chatData);
alert(this.state.chatData1);
})
.catch(error => {
console.log(error);
});
});
}
In class OpenedUser(), I have initialize in the constructor the code below
chatData: []
In the render method have implemented the code
<b> Load Message from Database for each user ({this.state.chatData1})</b>
<div>
{this.state.chatData.map((pere, i) => (<li key={i}>{pere.lastname} - {pere.id}----- {pere.username}</li>))}
</div>
Here is my Issue:
My problem is that the Axios Api is getting the result but am not seeing any result in the render method.
but I can see it in the console as per code below
Array(1)
0: {id: "1", firstname: "faco", lastname: "facoyo"}
length: 1
Here is an example of json api response.
[{"id":"1","firstname":"faco","lastname":"facoyo"}]
Here is the full code
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import { Link } from 'react-router-dom';
import axios from 'axios';
class User extends React.Component {
open = () => this.props.open(this.props.data.id, this.props.data.name);
render() {
return (
<React.Fragment>
<div key={this.props.data.id}>
<button onClick={() => this.open(this.props.data.id,this.props.data.name)}>{this.props.data.name}</button>
</div>
</React.Fragment>
);
}
}
class OpenedUser extends React.Component {
constructor(props) {
super(props);
this.state = {
chatData: [],
hidden: false,
};
}
componentDidMount(){
} // close component didmount
toggleHidden = () =>
this.setState(prevState => ({ hidden: !prevState.hidden }));
close = () => this.props.close(this.props.data.id);
render() {
return (
<div key={this.props.data.id} style={{ display: "inline-block" }}>
<div className="msg_head">
<button onClick={this.close}>close</button>
<div>user {this.props.data.id}</div>
<div>name {this.props.data.name}</div>
{this.state.hidden ? null : (
<div className="msg_wrap">
<div className="msg_body">Message will appear here</div>
<b> Load Message from Database for each user ({this.state.chatData1}) </b>
<div>
{this.state.chatData.map((pere, i) => (
<li key={i}>
{pere.lastname} - {pere.id}----- {pere.username}
</li>
))}
</div>
</div>
)}
</div>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
shown: true,
activeIds: [],
data: [
{ id: 1, name: "user 1" },
{ id: 2, name: "user 2" },
{ id: 3, name: "user 3" },
{ id: 4, name: "user 4" },
{ id: 5, name: "user 5" }
],
};
}
toggle() {
this.setState({
shown: !this.state.shown
});
}
open = (id,name) => {
alert(id);
alert(name);
//start axios api call
const user_data = {
uid: 'id',
uname: 'name'
};
this.setState({ loading_image: true }, () => {
axios.post("http://localhost/apidb_react/search_data.php", { user_data })
.then(response => {
this.setState({
chatData1: response.data[0].id,
chatData: response.data,
loading_image: false
});
console.log(this.state.chatData);
alert(this.state.chatData1);
})
.catch(error => {
console.log(error);
});
});
// end axios api call
this.setState((prevState) => ({
activeIds: prevState.activeIds.find((user) => user === id)
? prevState.activeIds
: [...prevState.activeIds, id]
}));
}
close = id => {
this.setState((prevState) => ({
activeIds: prevState.activeIds.filter((user) => user !== id),
}));
};
renderUser = (id) => {
const user = this.state.data.find((user) => user.id === id);
if (!user) {
return null;
}
return (
<OpenedUser key={user.id} data={user} close={this.close}/>
)
}
renderActiveUser = () => {
return (
<div style={{ position: "fixed", bottom: 0, right: 0 }}>
{this.state.activeIds.map((id) => this.renderUser(id)) }
</div>
);
};
render() {
return (
<div>
{this.state.data.map(person => (
<User key={person.id} data={person} open={this.open} />
))}
{this.state.activeIds.length !== 0 && this.renderActiveUser()}
</div>
);
}
}
The problem is you're making the request in the App component and storing in state but you're trying to access the state in a child component so it will never actually read the data.
To fix this you need to pass in the chat data via prop
<OpenedUser
chatData={this.state.chatData}
key={user.id}
data={user}
close={this.close}
/>
Note: In my runnable example, I've replaced your api endpoint with a mock api promise.
const mockApi = () => {
return new Promise((resolve, reject) => {
const json = [{ id: "1", firstname: "faco", lastname: "facoyo" }];
resolve(json);
});
};
class User extends React.Component {
open = () => this.props.open(this.props.data.id, this.props.data.name);
render() {
return (
<React.Fragment>
<div key={this.props.data.id}>
<button
onClick={() => this.open(this.props.data.id, this.props.data.name)}
>
{this.props.data.name}
</button>
</div>
</React.Fragment>
);
}
}
class OpenedUser extends React.Component {
constructor(props) {
super(props);
this.state = {
hidden: false
};
}
componentDidMount() {} // close component didmount
toggleHidden = () =>
this.setState(prevState => ({ hidden: !prevState.hidden }));
close = () => this.props.close(this.props.data.id);
render() {
return (
<div key={this.props.data.id} style={{ display: "inline-block" }}>
<div className="msg_head">
<button onClick={this.close}>close</button>
<div>user {this.props.data.id}</div>
<div>name {this.props.data.name}</div>
{this.state.hidden ? null : (
<div className="msg_wrap">
<div className="msg_body">Message will appear here</div>
<b>
{" "}
Load Message from Database for each user ({this.state.chatData1}
){" "}
</b>
<ul>
{this.props.chatData.map((pere, i) => (
<li key={i}>
{pere.lastname} - {pere.id}----- {pere.username}
</li>
))}
</ul>
</div>
)}
</div>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
shown: true,
chatData: [],
activeIds: [],
data: [
{ id: 1, name: "user 1" },
{ id: 2, name: "user 2" },
{ id: 3, name: "user 3" },
{ id: 4, name: "user 4" },
{ id: 5, name: "user 5" }
]
};
}
toggle() {
this.setState({
shown: !this.state.shown
});
}
open = (id, name) => {
alert(id);
alert(name);
//start axios api call
const user_data = {
uid: "id",
uname: "name"
};
// this.setState({ loading_image: true }, () => {
// axios
// .post("http://localhost/apidb_react/search_data.php", { user_data })
// .then(response => {
// this.setState({
// chatData1: response.data[0].id,
// chatData: response.data,
// loading_image: false
// });
// console.log(this.state.chatData);
// alert(this.state.chatData1);
// })
// .catch(error => {
// console.log(error);
// });
// });
this.setState({ loading_image: true }, () => {
mockApi().then(data => {
this.setState({
chatData1: data[0].id,
chatData: data,
loading_image: false
});
});
});
// end axios api call
this.setState(prevState => ({
activeIds: prevState.activeIds.find(user => user === id)
? prevState.activeIds
: [...prevState.activeIds, id]
}));
};
close = id => {
this.setState(prevState => ({
activeIds: prevState.activeIds.filter(user => user !== id)
}));
};
renderUser = id => {
const user = this.state.data.find(user => user.id === id);
if (!user) {
return null;
}
return (
<OpenedUser
chatData={this.state.chatData}
key={user.id}
data={user}
close={this.close}
/>
);
};
renderActiveUser = () => {
return (
<div style={{ position: "fixed", bottom: 0, right: 0 }}>
{this.state.activeIds.map(id => this.renderUser(id))}
</div>
);
};
render() {
return (
<div>
{this.state.data.map(person => (
<User key={person.id} data={person} open={this.open} />
))}
{this.state.activeIds.length !== 0 && this.renderActiveUser()}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I see a few missing points in your code namely you are using li without ul which is a kind of invalid markup, then you have mapping for .username which is undefined field according to response which may also throw error.

fetch data from api in Accordion list react native

I want to fetch the title from
https://facebook.github.io/react-native/movies.json
in accordion view in react native
how can i do this
here is my code but is display static data using array
now i want to display data from api
const dataArray = [
{
title: "First Element",
content:""
},
{
title: "Second Element",
content:
"content1"
},
{
title: "Third Element",
content:
"content2"
}
];
class LocationScreen extends Component {
componentDidMount(){
return fetch('https://facebook.github.io/react-native/movies.json ')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
return (
<Container>
<Content padder>
<Accordion
dataArray={dataArray}
/>
</Content>
</Container>
);
}
Replace {dataArray} by {this.state.dataSource}
render() {
return (
<Container>
<Content padder>
<Accordion
dataArray={this.state.dataSource}
/>
</Content>
</Container>
);
}
As suggest #slashsharp, use this.state.dataSource.
In the render method, you're using '{dataArray}' which is your static data.
If you want to start to display these static values, use this:
const dataArray = [
{
title: "First Element",
content:""
},
{
title: "Second Element",
content:
"content1"
},
{
title: "Third Element",
content:
"content2"
}
];
class LocationScreen extends Component {
state = {
dataSource: dataArray, //init state with your static data
}
componentDidMount(){
return fetch('https://facebook.github.io/react-native/movies.json ')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.data,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
return (
<Container>
<Content padder>
<Accordion
dataArray={this.state.dataSource} // changed to this.state.dataSource
/>
</Content>
</Container>
);
}
Change the
this.setState({
dataSource:responseJson.movies
}
and use dataArray={this.state.dataSource}
renderContent(section, _, isActive) {
return (
<Animatable.View
duration={400}
style={[
style.wrapServiceDesc,
isActive ? style.seriveActiveDesc : style.seriveInactiveDesc
]}
transition="backgroundColor"
>
<Animatable.Text
animation={isActive ? "bounceIn" : undefined}
style={[style.serviceDesc]}
>
{section.text} // fetch from API
</Animatable.Text>
</Animatable.View>
);
}
componentDidMount() {
const url = "url";
fetch(url)
.then(response => response.json())
.then(responseJson => {
this.setState({
dataSource: responseJson.data
});
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<Container>
<Content padder>
<Accordion
activeSections={activeSections}
sections={this.state.dataSource}
touchableComponent={TouchableOpacity}
expandMultiple={multipleSelect}
renderHeader={this.renderHeader}
renderContent={this.renderContent}
duration={400}
onChange={this.setSections}
/>
</Content>
</Container>
);
}
renderContent(section, _, isActive) {
return (
<Animatable.View
duration={400}
style={[
style.wrapServiceDesc,
isActive ? style.seriveActiveDesc : style.seriveInactiveDesc
]}
transition="backgroundColor"
>
<Animatable.Text
animation={isActive ? "bounceIn" : undefined}
style={[style.serviceDesc]}
>
{section.text} // fetch from API
</Animatable.Text>
</Animatable.View>
);
}
componentDidMount() {
const url = "url";
fetch(url)
.then(response => response.json())
.then(responseJson => {
this.setState({
dataSource: responseJson.data
});
})
.catch(error => {
console.log(error);
});
}
render() {
return (
<Container>
<Content padder>
<Accordion
activeSections={activeSections}
sections={this.state.dataSource}
touchableComponent={TouchableOpacity}
expandMultiple={multipleSelect}
renderHeader={this.renderHeader}
renderContent={this.renderContent}
duration={400}
onChange={this.setSections}
/>
</Content>
</Container>
);
}

Resources