Render component after fetch React Native - javascript

I have an app where a user is prompted to enter a code, it calls an external service and returns data from the api. Currently I'm able to enter the code and call the api and get a response back, I can also poll it every 10 seconds and return the data (no sockets on api service).
I have two components, showLanding and showResult.
When the app initialises, I want to show showLanding, prompt for a code and return showResult.
The problem I'm having is I'm not able to get it to 'update' the view.
I have tried ReactDOM.render or render() within the getScreen function, I feel as though I've missed something glaringly obvious when reading the React Native doco.
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {showLanding: true, showResult: false}
}
render() {
if (this.state.showLanding) {
return (
<View
tapCode={this.state.tapCode}
style={styles.appContainer}>
{this.state.showLanding && <LandingComponent/>}
</View>
);
}
if (this.state.showResult) {
return (
<View
tapCode={this.state.tapCode}
style={styles.appContainer}>
{this.state.showResult && <ResultComponent/>}
</View>
);
}
}
}
export class LandingComponent extends React.Component {
getResult = (value) => {
this.state = {
tapCode: value.tapcode
}
console.log(this.state);
this.getScreen(this.state.tapCode);
}
getScreen = (tapcode) => {
setInterval(() => (
fetch('https://mywebservice.com/' + this.state.tapCode)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.then(this.state = {
showLanding: false,
showResult: true,
tapCode: tapcode,
resultResponse: this.responseJson
})
.catch((error) => {
console.error(error);
})
), 10000);
}
render() {
return (
<View style={styles.landingContainer}>
landing view, prompt for code
</View>
);
}
}
export class ResultComponent extends React.Component {
render() {
return (
<View style={styles.resultContainer}>
Show json output
</View>
);
}
}

There are plenty solutions, but you should definitely consider using a navigation library like react-navigation or react-native-router-flux to handle routing transitions between components.
My "dirty" suggestion would be: Let the App-Component render your Landing-Page and put the state property 'showResults' in there. Show the code-input if showResult is false, if not, show results.
export class LandingComponent extends React.Component {
constructor(props){
super(props);
this.state = {
showResults: false,
tapcode: null,
resultResponse
}
getResult = (value) => {
this.setState({tapCode: value.tapcode})
this.getScreen(this.state.tapCode);
}
getScreen = (tapcode) => {
setInterval(() => (
fetch('https://mywebservice.com/' + this.state.tapCode)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
})
.then(function(res) {
this.setState({
showResult: true,
tapCode: tapcode,
resultResponse: res.json()})
return res;
})
.catch((error) => {
console.error(error);
})
), 10000);
}
render() {
return (
this.state.showResults ? <ResultComponent/> :
<View style={styles.landingContainer}>
call fetch here....
</View>
);
}
}
And please never mutate your state directly! Call setState() instead.

You need to move the API call up to App. Right now, showLanding is part of the App's state, but you're setting in the LandingComponent so you're not triggering a re-render.

Related

Use static fetch service

I have created an express mongoose api. I want to use that api from my React-application.
I want to create a service that would manage those api requests. But I am new in react-native and I can't use that service. I tried creating a static class but I cannot make it works. Here is an example :
// apiService.js
class ApiService {
static fetchUsers = () => {
return fetch('XXX/users')
.then((response) => {
return response.json()
.then((data) => {
return data;
})
})
.catch((error) => {
console.error(error);
});
}
}
export default ApiService;
And my screen
// UserScreen.js
import ApiService from '../services/apiService';
export default class UserScreen extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
isLoading: true,
}
}
componentDidMount = () => {
let users = ApiService.fetchUsers();
this.setState({data: users});
this.setState({isLoading: false});
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator/>
</View>
)
} else {
return (
<View style={{ flex: 1, marginTop: 100 }}>
{
this.state.data.map((val, key) => {
return <TouchableOpacity
style={styles.homeButton}
key={key}
onPress={() => this.redirectHandler(val)}>
</TouchableOpacity>
})
}
</View>
)
}
}
}
I tried using async and wait but I can't find a way to retrieve data. The data are well retrieve in the apiService but I can't share them with the UserScreen.
How can I use a (static or not) class/function in react-native and get the data from the screen
Update
Here is what I tried with async
class ApiService {
static fetchUsers = async () => {
try {
let response = await fetch('XXXXX/users/');
let json = await response.json();
return json;
} catch (error) {
console.error(error);
}
}
}
export default ApiService;
And in my Userscreen
componentDidMount = async () => {
try {
let users = await ApiService.fetchUsers();
this.setState({isLoading: false});
this.setState({data: users});
} catch (error) {
console.log(error);
}
}
The problem lies in the setState that you are performing twice. If you look at the logic of the component, first we check for isLoading, if true we show some message/spinner otherwise we are showing a list of users/data.
Sequence of the Set State:
this.setState({isLoading: false});
this.setState({data: users});
Note that each setState triggers a re-render of the component, so in this case first we set isLoading to false (1st Re-Render) and then we set the data (2nd Re-Render)
The problem is, when 1st Re-Render is done, isLoading is set to false and the condition which we talked about above, now enters the "showing the user/data list" part. Another thing to note here is we have defined users: [] in state and when we are setting the users array (from the api call), we set that in a variable called data. The variable data is never defined in state so essentially it is "undefined".
Issue in your code:
this.state.data.map(...)
You cannot map over an undefined variable and this is where the problem lies. Doing so will throw an error saying "cannot read property map of undefined".
To fix this:
When setting the users list, instead of doing this.setState({ data: users }) just do this.setState({ users: users }) and change this.state.data.map( to users.map(
Also, unnecessary re-renders are costly and in case of React Native, they are costlier. Merge your setState(...) calls when possible. For example,
this.setState({
isLoading: false,
users: users
})

Undefined is Not an Object (evaluating 'this.state.data.confirmed.value')

I am new to React Native and practicing by creating a project which makes requests from a COVID-19 API. However, when I run my code, I get this error:
TypeError: undefined is not an object (evaluating 'this.state.data.confirmed.value')
import React from 'react';
import { View, Text } from 'react-native';
class TrackerScreen extends React.Component {
state = {
data: ''
}
componentDidMount = () => {
fetch('https://covid19.mathdro.id/api', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<View>
<Text>
{this.state.data.confirmed.value}
</Text>
</View>
)
}
}
export default TrackerScreen;
I converted my componentDidMount to an arrow function as suggested by other members on an old thread but that did not get rid of the error. Does anybody have a solution to this issue? Any help would be appreciated. Thank you!
The first render will happen before the componentDidMount will be called. So, during the first render the data property from your state will be an empty string. And the code inside the render function is trying to access a nested prop. Either provide a more described state, like:
state = {
data: { confirmed: { value: null } }
}
or check the value inside the render function:
import React from 'react';
import { View, Text } from 'react-native';
class TrackerScreen extends React.Component {
state = {
data: ''
}
componentDidMount = () => {
fetch('https://covid19.mathdro.id/api', {
method: 'GET'
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
render() {
const { data: {confirmed: { value } = { value: null } } } = this.state
return value ? (
<View>
<Text>
{value}
</Text>
</View>
): null;
}
}
export default TrackerScreen;
You probably don't want to render anything if the data isn't present at the moment, so an additional check for the value will handle that

Using useEffect with class Components

I have a class used to render a list of users from a database
export default class Users extends React.Component {
constructor() {
super()
this.state = {
data : [] //define a state
}
}
renderUsers = () => {
useEffect(() => {
fetch('exemple.com')
.then((response) => response.json())
.then((json) => this.setState({data: json.result})) // set returned values into the data state
.catch((error) => console.error(error))
}, []);
return this.state.data.map((value,key)=>{ // map state and return some views
......
})
}
render() {
return (
<View style={{ flex: 1 }}>
{this.renderUsers()} //render results
</View>
);
}
}
The problem is this code will throw the following error :
Invalid Hook call, Hooks can be called only inside of the body
component
I think is not possible to use hooks inside class component..
If it's not possible what is the best approach to fetch data from server inside this class ?
You cannot use hooks in a class component. Use componentDidMount instead.
Hooks can be used only in functional components.
You could rewrite your component to be a functional one like so:
export default Users = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('exemple.com')
.then((response) => response.json())
.then((json) => setData(json.result)) // set returned values into the data state
.catch((error) => console.error(error))
}, []);
const renderUsers = () => {
return data.map((value, key) => {
// DO STUFF HERE
})
}
return (
<View style={{ flex: 1 }}>
{renderUsers()} //render results
</View>
)
}

Consuming Paginated API in React Component

I'm just getting started with React. As a simple exercise, I wanted to create some components for viewing data retrieved from the JsonMonk API. The API contains 83 user records and serves them in pages of 10.
I am trying to develop a component for viewing a list of users one page at a time which I called UserList. The code for it is below:
class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {
pageNumber: 1,
users: [],
};
this.onPageNext = this.onPageNext.bind(this);
}
componentDidMount() {
this.fetchUsers(this.state.pageNumber)
.then((users) => this.setState({users: users}));
}
async fetchUsers(pageNumber) {
const response = await fetch(`https://jsonmonk.com/api/v1/users?page=${pageNumber}`);
const jsonResponse = await response.json();
return jsonResponse.data.records;
}
onPageNext() {
// ...
}
render() {
const postElements = this.state.users.map(
(props) => <User key={props._id} {...props} />);
return (
<div>
{postElements}
<div>
<button onClick={this.onPageNext}>Next</button>
</div>
</div>
);
}
}
The problem I am having pertains to the onPageNext method of my component. When the user clicks the "Next" button, I want to make a fetch for the next page of data and update the list.
My first attempt used an asynchronous arrow function passed to setState like so:
onPageNext() {
this.setState(async (state, props) => {
const nextPageNumber = state.pageNumber + 1;
const users = await this.fetchUsers(nextPageNumber);
return {pageNumber: nextPageNumber, users: users}
})
}
However, it does not seem React supports this behavior because the state is never updated.
Next, I tried to use promise .then syntax like so:
onPageNext() {
const nextPageNumber = this.state.pageNumber + 1;
this.fetchUsers(nextPageNumber)
.then((users) => this.setState({pageNumber: nextPageNumber, users: users}));
}
This works but the problem here is that I am accessing the class's state directly and not through setState's argument so I may receive an incorrect value. Say the user clicks the "Next" button three times quickly, they may not advance three pages.
I have essentially run into a chicken-or-the-egg type problem. I need to pass a callback to setState but I need to know the next page ID to fetch the data which requires calling setState. After studying the docs, I feel like the solution is moving the fetch logic out of the UsersList component, but I'm not entirely sure how to attack it.
As always, any help is appreciated.
You need to change onPageNext as below:
onPageNext() {
this.setState( prevState => {
return {pageNumber: prevState.pageNumber + 1}
}, () =>{
this.fetchUsers(this.state.pageNumber).then(users => this.setState({users: users}) )
});
}
Here is the Complete Code:
import React from "react";
export default class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {
pageNumber: 1,
users: [],
};
this.onPageNext = this.onPageNext.bind(this);
}
componentDidMount() {
this.fetchUsers(this.state.pageNumber)
.then((users) => {
console.log(users, 'users');
this.setState({users: users})
}
);
}
async fetchUsers(pageNumber) {
const response = await fetch(`https://jsonmonk.com/api/v1/users?page=${pageNumber}`);
const jsonResponse = await response.json();
return jsonResponse.data.records;
}
onPageNext() {
this.setState( prevState => {
return {pageNumber: prevState.pageNumber + 1}
}, () =>{
this.fetchUsers(this.state.pageNumber).then(users => this.setState({users: users}) )
});
}
render() {
const postElements = this.state.users.map(
(user) => <User key={user._id} {...user} />);
return (
<div>
{postElements}
<div>
<button onClick={this.onPageNext}>Next</button>
</div>
</div>
);
}
}
function User(props) {
return (
<div>
<div style={{padding: 5}}>Name: {props.first_name} {props.last_name}</div>
<div style={{padding: 5}}>Email: {props.email}</div>
<div style={{padding: 5}}>Phone: {props.mobile_no}</div>
<hr/>
</div>
);
}
Here is the Code Sandbox

API taking too long, map function firing before data loads

import React, { Component } from 'react';
import {withProvider} from './TProvider'
import ThreeCardMap from './ThreeCardMap';
class Threecard extends Component {
constructor() {
super();
this.state = {
newlist: []
}
}
componentDidMount(){
this.props.getList()
this.setState({newlist: [this.props.list]})
}
// componentDidUpdate() {
// console.log(this.state.newlist);
// }
render() {
const MappedTarot = (this.state.newlist.map((list, i) => <ThreeCardMap key={i} name={list.name} meaningup={list.meaning_up} meaningdown={list.meaning_rev}/>);
return (
<div>
<h1>Three Card Reading</h1>
<div>{ MappedTarot }</div>
</div>
)
}
}
export default withProvider(Threecard);
Hi, I'm trying to create a page that takes data from a tarot card API (https://rws-cards-api.herokuapp.com/api/v1/cards/search?type=major). Unfortunately by the time the data comes in, my map function has already fired. I'm asking to see if there is a way to have the map function wait until the data hits before it fires. Thanks!
Edit: getList function in the Context:
getList = () => {
console.log('fired')
axios.get('https://vschool-cors.herokuapp.com?url=https://rws-cards-api.herokuapp.com/api/v1/cards/search?type=major').then(response =>{
this.setState({
list: response.data
})
}).catch(error => {
console.log(error);
})
}
this.props.getList() is an async function. You are setting the list right after that call which is not correct.
You need to set it in the getList promise then() block.
getList() is an async function and update data for the parent component. So, my solution is just watching the list from the parent component if they updated or not, through getDerivedStateFromProps
class Threecard extends Component {
constructor() {
super();
this.state = {
newlist: []
}
}
// Set props.list to this.state.newList and watch the change to update
static getDerivedStateFromProps(nextProps, prevState) {
return {
newlist: nextProps.list
}
}
componentDidMount(){
this.props.getList()
// Removed this.setState() from here.
}
render() {
const MappedTarot = (this.state.newlist.map((list, i) => <ThreeCardMap key={i} name={list.name} meaningup={list.meaning_up} meaningdown={list.meaning_rev}/>);
return (
<div>
<h1>Three Card Reading</h1>
<div>{ MappedTarot }</div>
</div>
)
}
}
export default withProvider(Threecard);

Categories

Resources