E
E
Eugene2019-03-05 17:39:47
JavaScript
Eugene, 2019-03-05 17:39:47

Why is getInitialProps not called when the component is loaded?

I make the transition from the main page to the "technology" page:

render() {
        return (
            <Link href={{pathname: '/technology', query: {technology: this.props.title}}}>
                <a
                    ref={this.getLessonBlockRef}
                    className='lessonBlock'
                    style={{backgroundColor: this.props.backgroundColor,}}
                >
                    { this.props.title }
                </a>
            </Link>
        );
    }

But the "technology" page aka component does not call getInitialProps:
TechnologyPage.getInitialProps = async ({store, req, query}) => {
    console.log("GET INITIAL PROPS PAGE TECHNOLOGY!");
    try {
        const response = await axios.get(`${req.protocol}://${req.get('Host')}/api/getTechnologySections`, {params: {technology: query.technology}});
        store.dispatch({type: 'getTechnologySections', payload: response.data});
    } catch (error) {
        console.log(error);
    }
};

But! If I go to the "technology" page directly through the address bar (I type in the path to this page), then everything works. Why is that? Who can explain this strange behavior?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2019-03-05
@Shagfey

In general, the solution is:
1. When you download the application for the first time, it is loaded from the server. And the data for all urls are taken from the server. In the future, everything is taken from the client.
2. This code is working:

TechnologyPage.getInitialProps = async ({store, req, query}) => {
    try {
        let response = null;
        if (process.browser) {
            response = await axios.get(`${window.location.protocol}/api/getTechnologySections`, {params: {technology: query.technology}});
        } else {
            response = await axios.get(`${req.protocol}://${req.get('Host')}/api/getTechnologySections`, {params: {technology: query.technology}});
        }
        store.dispatch({type: 'getTechnologySections', payload: response.data});
    } catch (error) {
        console.log(error);
    }
};

This should be done in every component.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question