How to retrieve data from `window` object - React?

2.3k views Asked by At

I am super new to ReactJS. I am trying to assign third party script file to my Window obbject like below code in my componentDidmount method.

        const script = document.createElement("script");
        script.src = "www.xxx.com/src/data.js";
        script.async = true;
        document.body.appendChild(script);
        console.log(window);

from last console log, I get full window object with third party scripts's data. But next I tried to a set that data to my state like below in same component after above code.

           this.setState({
                dataBook: window.databook,
                dataTopic: window.datatopic
            }) 

but state assigned as undefined. I tried using Helmet and script-tag npm as well. I think I am not doing it right. How to retrieve data from window object? Thanks Full component

import React from 'react';
import './App.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            url:"https://example.com/src/customdata.js",
            dataBook: [],
            dataTopic: [],
            dataLesson: [],
            dataGloss: []
        }
    }

    componentDidMount() {
        const script = document.createElement("script");
        script.src = this.state.url;
        script.async = true;
        document.body.appendChild(script);
        console.log(window);

        this.setState({
                dataBook: window.databook,
                dataTopic: window.datatopic,
                dataLesson: window.datalesson,
                dataGloss: window.datagloss
            })
    }

    render() {
        return (
            <div className="App">
                <div>Book Titles</div>
                {
                    window.databook.map((item)=>{
                        console.log(item)
                    })
                }
                <hr/>

            </div>
        );
    }

}

export default App;

0

There are 0 answers