Raydot
Raydot

Reputation: 1586

Call a function on application startup in react

I'm trying to call a function from application startup. The function reads data from JSON via dataVar (set elsewhere) and tries to load it into {items} for further consumption:

const dataVar = JSONStuff;    
class Global extends Component {
        constructor(props) {
        super(props);
        this.state = {
            query: '',
            items: []
        }

        this.init();

    } 

    // componentDidMount() {
    // This doesn't work either!
    //  this.init();
    // }

    init() {
        let { items } = dataVar;
        this.setState({items});
    }


    render() {
        return (
            <div className="Global">
                    <Gallery items={this.state.items}/>
            </div>
        )
    }
}

Then in Gallery.js:

import React, { Component } from 'react';

class Gallery extends Component {
    render() {
        return (
            <div>
                <h3>gallery:</h3>
                {
                    this.props.items.map((item, index) => {
                        let {title} = item.name;
                        return (
                            <div key={index}>{title}</div>
                        )
                    })
                }
            </div>
        )
    }
}

export default Gallery;

Not sure why Global can't call a function inside of itself. I've tried with and without "this." I either get error to where the app won't complile or I get:

"Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op."

Upvotes: 0

Views: 11513

Answers (1)

Bill
Bill

Reputation: 19248

First of all, it's a warning, you probably better not call setState in componentDidMount.

My suggestion 1: assign value to state in constructor

constructor(props) {
  super(props);

  this.state = {
    query: '',
    items: dataVar.items,
  };
}

Suggestion 2:

Do inside the componentWillReceiveProps

componentWillReceiveProps(nextProps) {
  const { dataVar: items } = nextProps; // pass dataVar as props
  this.setState({
    items,
  });
}

Plus try to debug your props and pay attention on your console for errors.

Upvotes: 1

Related Questions