0

I'm unable to pass data assigned to a const through props in react-js. When I check the same in console.log i see a null object.

Below is code for the function.

updateList() {
    // temporary dictionary
    const keywords = {}
    const taxonomies = {}
    const { master, selectedRank, selectedCategory } = this.state
    console.log(`master[${selectedRank}][${selectedCategory}]`)

    if (master && master[selectedRank] && master[selectedRank][selectedCategory]) {
        console.log(`master[${selectedRank}][${selectedCategory}]`, master[selectedRank][selectedCategory])
        const filterData = master[selectedRank][selectedCategory]
        master[selectedRank][selectedCategory].forEach(d => {
            keywords[d.keywordId] = d.keywordName;
            taxonomies[d.taxId] = d.taxonomyName;
        })

        const keywordsOptions = Object.keys(keywords).map(key => { return { id: key, name: keywords[key] }; });
        const taxonomyOptions = Object.keys(taxonomies).map(key => { return { id: key, name: taxonomies[key] }; });

        this.setState({
            filterData
        })
        console.log("Filtered Data", this.state.filterData)
        this.setState({
            keywordsOptions,
            selectedKeywordsOptions: keywordsOptions.slice(),
            taxonomyOptions,
            selectedTaxonomyOptions: taxonomyOptions.slice(),
            filterKeyword: [],
            filterTaxonomy: [],
        }, () => {
            this.updateChart();
        });
    }
}

I want to pass the data assigned to const filterData through props to a component in another js file. Though I'm setting up the state within the function I always get a null object in console. When I'm pushing the const to console I see the associated data being displayed in console.

I tried various other ways but none of them seem to be working here.

Thanks in advance.

Regards,

Rohit K
  • 128
  • 1
  • 12
  • 1
    `setState` is asynchronous, somehow, from the code you know that already, because you update your chart only when it is completed, so why do you expect it to be different for `filterData`? One more nitpick, yeah semi colons are optional in javascript, but using them consistent and not sometimes yes, sometimes not, will also make your code a lot more readable (I favor them always) – Icepickle Apr 07 '18 at 07:49
  • I want to use the same filtered data for other charts instead of calling the API again. Is there anything I'm missing here? – Rohit K Apr 07 '18 at 07:52
  • Are your all your charts being rendered from this component? If not, then the filteredData may not be in the correct component (maybe, a component higher where that data is passed through props, so that your charts rely on the same data would make more sense) – Icepickle Apr 07 '18 at 07:55

0 Answers0