user6398538
user6398538

Reputation:

Do I always need a state whenever I am sending data from express to react

Hi guys I am wondering if do i always need a state whenever I am trying to send data from express to react.

For instance, I have a file here for my server.js:

const express = require('express');
const router = express.Router();

router.get('/', (req, res, next) =>{
  res.send({'name': 'bella'})
});

module.exports = router;

This simply sends me an to the screen and when I try to render and use this on my react via localhost 3000 I try to use this:

class MainApp extends React{

  componentDidMount() {
    this.getInitial();
  }

  getInitial() {
    fetch('/')
    .then((resp) => resp.json())
    .then(data => console.log('got the data back >>>>>>>>', data))
    .catch((err) => console.log(err));
  }

  render(){
    return (
      <div>
        <h1>HELLO WORLD FROM REACT CLIENT FRONTEND {data.name}!</h1>
      </div>
    );
  }
}

Unfortunately, that did not work and it seems that the server is the one being rendered not the react file on the front end - localhost:3000. I am also not receiving any console.log as define at my fetch.

Any idea? Sorry I am just curious and newbie here. Thanks in advance!

PS. Is it also possible to send some static text from Express and then render it on React frontend?

Upvotes: 0

Views: 37

Answers (1)

Kenneth Truong
Kenneth Truong

Reputation: 4176

Yes you do need a state. You need to let React know when to call the render method again.

setState helps you do that by letting React know that state has changed and to re-render. If you store your data in this.data React won't know that anything changed

You should update your code to something like this

constructor(props) {
  super(props);

  this.state = {
    data: null
  };
}  


getInitial() {
  fetch('/')
    .then((resp) => resp.json())
    .then(data => {
      this.setState({ data });
    })
    .catch((err) => {
      console.log(err) 
      // You can also setState here to display an error message
    });
}

render() { 
  // You have access to this.state.data 
}

Upvotes: 1

Related Questions