Olalekan Olalekan - 1 year ago 71
Javascript Question

ReactJS: What is the correct way to set a state value as array?

I have an array of object that get users data using fetch API. I have tried constructor, create a function, bind it. It didn't work. I tried ComponentDidMount and setState, it returns undefined.

class Admin extends Component {

componentDidMount () {

var that = this;
fetch('http://localhost:4500/data/users', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}).then(function(response) {
return response.json();
that.state = {users: json};


render() {

return (


What is the correct way to set a state value as array and render it? Thanks

Answer Source

First initialize your state in your constructor like this

constructor(props) {
        this.state = {users : []} //initialize as array

Then instead of that.state = {users: json}; set your state using

that.setState({ users: json });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download