0

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) {
        super(props);
        this.state = {
            bunny: [],
            loaded: false
        }
    }

    componentDidMount = () => {
        (async function(){
            let bugs = await axios.get('/api/vault/', {
                headers: {'Authorization': "JWT " + sessionStorage.getItem('token')}
            });
            let hiren = [];
            bugs.data.forEach(async data => {
                let temp = {};
                temp['id'] = data.id;
                temp['site_url'] = data.site_url;
                temp['tag'] = data.tag;
                temp['email'] = await decrypt(sessionStorage.getItem('key'), data.email);
                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;

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

    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 (
                <div>
                    <Helmet
                        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>
                    </BootstrapTable>
                </div>
            )
        }
        return <div>loading.... </div>
    }
}

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

5
  • 1
    I think you have a syntax error. You're probably not pushing into bunny. Commented Aug 11, 2016 at 13:01
  • show console.log of hiren just before this.setState({bunny: hiren}); Commented Aug 11, 2016 at 13:02
  • also i would dont call setState multiple times, each time you call setState render function is called which is not required if you club all updates in a single state update call Commented Aug 11, 2016 at 13:05
  • @Maxx empty array [ ] Commented Aug 11, 2016 at 13:12
  • @pyprism well, it means nothing pushed to your array, try to console log bugs, may be you get empty response from server Commented Aug 11, 2016 at 13:23

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.