pyprism pyprism - 1 year ago 241
React JSX Question

ReactJS correct way to push array type state

I have an empty state array, when I try to change the state using react-addons-update I got this error

invariant.js:38 Uncaught (in promise) Error: update(): expected target of $push to be an array; got [object Object].(…)
. Here is the code :

import React from 'react';
import ReactDOM from 'react-dom';
import Helmet from "react-helmet";
import axios from 'axios';
import { browserHistory } from 'react-router';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import {encrypt, decrypt} from '../utils/pgp.js';
import update from 'react-addons-update';

export default class Passwords extends React.Component {
constructor(props) {
this.state = {
bunny: [],
loaded: false

componentDidMount = () => {
(async function(){
let bugs = await axios.get('/api/vault/', {
headers: {'Authorization': "JWT " + sessionStorage.getItem('token')}
let hiren = []; data => {
let temp = {};
temp['id'] =;
temp['site_url'] = data.site_url;
temp['tag'] = data.tag;
temp['email'] = await decrypt(sessionStorage.getItem('key'),;
temp['username'] = await decrypt(sessionStorage.getItem('key'), data.username);
temp['password'] = await decrypt(sessionStorage.getItem('key'), data.password);
temp['note'] = await decrypt(sessionStorage.getItem('key'), data.note);
temp['created_at'] = data.created_at;
temp['updated_at'] = data.updated_at;

//this.setState({bunny: hiren}); <-- renders empty table
this.setState(update(this.state, {$push: hiren}));
this.setState({loaded: true});

render() {

function anchor(cell, row){
let a;
if (cell.startsWith('http://'))
a = cell.slice(7);
else if (cell.startsWith('https://'))
a = cell.slice(8);
return '<a href=' + cell + '>' + a + '</a>' ;
if(this.state.loaded) {
return (
title="Vault-> Passwords"
<BootstrapTable data={this.state.bunny} striped={true} hover={true} condensed={true} pagination={true} search={true}>
<TableHeaderColumn dataField="id" isKey={true}>ID</TableHeaderColumn>
<TableHeaderColumn dataField="site_url" dataFormat={anchor} dataSort={true}>URL</TableHeaderColumn>
<TableHeaderColumn dataField="email">Email</TableHeaderColumn>
<TableHeaderColumn dataField="username">Username</TableHeaderColumn>
<TableHeaderColumn dataField="password">Password</TableHeaderColumn>
<TableHeaderColumn dataField="note">Note</TableHeaderColumn>
<TableHeaderColumn dataField="tag">Tag</TableHeaderColumn>
<TableHeaderColumn dataField="created_at">Created At</TableHeaderColumn>
<TableHeaderColumn dataField="updated_at">Updated At</TableHeaderColumn>
return <div>loading.... </div>

So what is the correct way to push arrays in state ?

Answer Source

Try with this.setState(update(this.state, {bunny: { $push: hiren } }))
And you are using async functions in your forEach. variable hiren will be empty by the time setState is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download