Monday, 31 May 2021

SSR with data fetch without state management library

I am trying to make a SSR react app, but not able to pass props from express to the component. What mistake am i doing?

server.js

import AppPage2 from './src/project02/LandingPage';
......
......
server.get('/project2',async (req,res)=>{
    const context = {data:'test'}
    const sheet = new ServerStyleSheet();
    const content = ReactDOMServer.renderToString(sheet.collectStyles(
        <StaticRouter location={req.url} context={context}>
            <AppPage2 state=/>
        </StaticRouter>)
    );
    const styles = sheet.getStyleTags();
    let html = appShell( 'Project 2', content,' project2.bundle.js',styles)
    res.status(200).send(html);
    res.end()
})

AppPage2(./src/project02/LandingPage)

import React from 'react';
import {Wrapper,Title}  from './styleComponent/testStylePage'
.......
.......
class AppPage extends React.Component {

    componentDidMount() {
       console.log("",this,this.props, this.props.staticContext)
    }

    render(){
        return(
            <Wrapper>
                <Title>This is project 01 </Title>
            </Wrapper>
        )
    }
}

export default AppPage;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import AppPage from './project02/LandingPage'

ReactDOM.hydrate(
        <AppPage></AppPage>,
    document.querySelector('#root')
);

webpack.client.conf

const path = require('path');
const glob = require("glob");
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;


const entry = glob.sync("src/*.js")
    .reduce((x, y) => Object.assign(x, 
        {
            [y.replace('src/','').replace('.js','')]: `./${y}`,
        }
), {});


    
    module.exports = {
            target: 'node',
            mode: 'development',//development,production
            entry: entry,
            output: {
                filename:'[name].bundle.js',
                path: path.resolve(__dirname,'build/public/'),
                publicPath: '/build/'
            },
            module: {
                rules: [
                    {
                        test: /\.js$/,
                        exclude: /(node_modules)/,
                        use: {
                            loader: 'babel-loader'
                        },
                        
                    },
                ]
            },
            plugins: [
                // new BundleAnalyzerPlugin()
            ]
        }

I am not able to log console.log("",this,this.props, this.props.staticContext) from AppPage2(./src/project02/LandingPage) this page i am sending data from server.js(express)



from SSR with data fetch without state management library

No comments:

Post a Comment