reactjs


React failed to set state in the function invoked inside componentWillMount()


I am new to react. I am trying to fetch data from remote server using _fetchUsers() dynamically. The state apiUrl should be changed when clicking different nav tabs, although not showing here. The problems, I find that, the log before $.ajax function shows empty string of this.state.apiurl. If I hardcode the url on ajax's url property, the ajax can return right response. Can someone explain why I fail to setState for the apiurl, is the reason related to componentWillMount()
export default class RegiteredUserTable extends Component {
constructor() {
super();
this.state = {
registeredUsers:[],
tableProperties:[],
apiUrl:''
}
}
_fetchUsers() {
console.log("this.props", this.props);
if(this.props.match.params.tableId === "buyer-table"){
this.setState({apiUrl:'/buyers/list-buyers'});
} else if (this.props.match.params.tableId === "seller-table") {
this.setState({apiUrl:'/sellers/list-sellers/'});
}
console.log('this.state.apiUrl',this.state.apiUrl);
$.ajax({
method: 'GET',
url: `${this.state.apiUrl}`,
success: (res) => {
console.log('res',res);
let registeredUsers = res.data;
this.setState({registeredUsers});
}
});
}
_getTableProperty() {
//property array
console.log('this.state.registeredUsers',this.state.registeredUsers);
const tableProperties = this.state.registeredUsers[0].keys;
this.setState({tableProperties});
return tableProperties.map(tableProperty => {
return (
<th>{tableProperty}</th>
)
})
}
_getUsers() {
return this.state.registeredUsers.map(registeredUser => {
return (
<tr>
<td>{registeredUser.id}</td>
<td>{registeredUser.first_name}</td>
<td>{registeredUser.last_name}</td>
</tr>
);
}
)
}
componentWillMount() {
this._fetchUsers();
}
render() {
return(
<div className="container">
<div className="row">
<div className="col-xs-12">
<div className="table-responsive">
<table className="table table-bordered table-hover">
<caption className="text-center">Agents' data</caption>
<thead>
<tr>
{this._getTableProperty()}
</tr>
</thead>
<tbody>
{this._getUsers()}
</tbody>
<tfoot>
<tr>
<td colSpan="5" className="text-center">Data retrieved from infoplease and worldometers.</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
);
}
}
SetState is async, so do the api call once setState set the apiUrl in state variable, use a callback method and do the api call inside that.
Write the _fetchUsers like this:
_fetchUsers() {
let tableId = this.props.match.params.tableId;
this.setState({
apiUrl: tableId === "buyer-table" ? '/buyers/list-buyers' : '/sellers/list-sellers/'
}, () => {
$.ajax({
method: 'GET',
url: `${this.state.apiUrl}`,
success: (res) => {
console.log('res',res);
let registeredUsers = res.data;
this.setState({registeredUsers});
}
});
});
}
Or better way will be just store the apiUrl in a variable and do setState once you get the response, by that way you don't need to do setState twice and don't need to depend on first setState.
Like this:
_fetchUsers() {
let tableId = this.props.match.params.tableId;
let url = tableId === "buyer-table" ? '/buyers/list-buyers' : '/sellers/list-sellers/';
$.ajax({
method: 'GET',
url: url,
success: (res) => {
console.log('res',res);
let registeredUsers = res.data;
this.setState({registeredUsers, apiUrl: url});
}
});
}

Related Links

nested url routing using react-router and webpack dev server
How to split up modules for each react-router path with browserify
React Component does not update when receiving an array of objects with reverse order. What can I do to make it updated?
React Native skips in-between rendering
react redux split reducer change prev state
material-ui component properties not working
Performance issues with a tree structure and shouldComponentUpdate in React / Redux
How do I subscribe to React's global virtual events?
React - differentiating between dynamically generated inputs on a form
Redux action creators state access best practices
componentDidMount() not being called when react component is mounted
Is an anti-pattern returning undefined or null inside componentWillReceiveProps?
How to remove a component from an array in Reactjs
Update react component without parent outside of it
React Form Component onSubmit Handler Not Working
React (Jest tests for tr element Unable to find element…tbody)

Categories

HOME
drupal
skype-for-business
indexing
swift3
query-string
mailchimp
sdk
glympse
flowtype
schema
tracking
tmux
fastreport
swift3.1
github-flavored-markdown
minimum
css-float
accordion
project-structure
spring-webflow
single-page-application
ajaxcontroltoolkit
xna
aws-iot
policy
jira-zephyr
grunt-contrib-uglify
deployment-descriptor
mex
uibarbuttonitem
andengine
imageprocessor
android-geofence
var
motion
office-interop
ssdp
scrapinghub
codepen
api-key
niagara-ax
serverless-architecture
text-formatting
remap
hdpi
skype-bots
visualizer
programming-pearls
dmalloc
rmq
trusted-computing
android-tabs
access-violation
init
sprockets
weblogic-maven-plugin
jmh
mod
clique
dcast
methodology
wordpress-plugin
web-performance
wiql
serial-communication
redquerybuilder
pdcurses
photogrammetry
genero
pymol
mind-manager
apache-pivot
powerpoint-2010
drawable
reactjs-native
nvcc
randomaccessfile
infomaker
static-class
kohana-orm
codeigniter-form-helper
mysql2
nsautoreleasepool
nx
mmo
phone-state-listener
qt5.1
feincms
invalidoperationexception
gssapi
expresso-store
netbiscuits
big-endian
xcode4.6.3
blackberry-eclipse-plugin
helicontech
idtabs
visual-leak-detector
cgaffinetransform
execjs
mismatch
n2
html5-animation
javah
conditional-operator
datarelation
simultaneous
manuals

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile