1

The state does not seem to change or rerender. I have tried logging from inside the useEffect and nothing happens. Any idea how to get the useEffect working?

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var app = express();

// view engine setup
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.get('bots/burrito', function(req, res, next) {
    //res.render('bot')
    res.render('bot')
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.log(err)
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

bot.jsx

import React from 'react';

const tutorials=(props)=>{
    const [a, setA] = React.useState('asdf')
    React.useEffect( ()=>{
       setA('asdfasfdasdfa')
    }, [] );
    return(
        <p>{a}</p>
    )
 }


module.exports = tutorials;

When I navigate to https://localhost:3000/bots/burrito I see the rendered <p>asdf</p> and it never changes.

2
  • If you are doing Server Side Rendering the useEffect hook won't work. I just did a quick google search.... there are answers. I'm not familiar with SSR enough to suggest any of them though.
    – Drew Reese
    Jan 9, 2021 at 1:38
  • You are just returning the rendered html from the server, not the react script itself.
    – BeS
    Jan 9, 2021 at 1:38

1 Answer 1

1

express-react-views calls ReactDOM.renderToStaticMarkup under the hood. that function returns the initial HTML for your component and does not attempt to apply hooks, as mentioned here:

If you use server rendering, keep in mind that neither useLayoutEffect nor useEffect can run until the JavaScript is downloaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.