Kirill Stas Kirill Stas - 1 month ago 14
React JSX Question

Get data from express with fetch

I try to

alert
string which is variable in express.get and do to res. I wanna get in alert this "I am working fetch".

Here my server.js

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/publicServer'));

app.get('/fimlList', function(req, res) {
console.log('i receive a GET request');

var tryFetch = {myString: 'I am working fetch'};

res.json(tryFetch)
})

app.listen(3000);
console.log('Server running on port 3000');


my App.js

import React from 'react';

var IchBinForm = require('./IchBinForm');
var SortFilms = require('./SortFilms');
var SearchFilm = require('./SearchFilm');
var FilmShort = require('./FilmShort.js');
var FilmLong = require('./FilmLong.js');

var App = React.createClass({
getInitialState: function() {
return {
list: {}
},

componentWillMount: function(){
var fromServer = fetch('/fimlList')
.then(function(response) {
return response.json()
})
.then(function(responseJson) {

return responseJson.myString
})

alert(fromServer);

},

changeShow: function(newShow, filmId) {...},
deleteFilm: function(id) {...},
seeForChangeInForm: function(change, id) {...},
addNewFilm: function() {...},
sortMe:function() {...},
searchMe: function(searchWord) {...},
howSearch:function(whichCheckBox, val) {...},

render: function() {

....
}
}

});

return (...);
}
});

module.exports = App;


and what I get:

My alert now

What do I do wrong ?

Answer

You assign fromServer with a promise from fetch... You try to write code as it was synchronously while in fact it's asynchronously

Either move the code inside the last then function

.then(function(responseJson) {
    console.log(responseJson)
})

or use async/await to get a synchronously feeling while writing code

async function(){
    var fromServer = await fetch('/fimlList')
    .then(function(response) {
      return response.json()
    })
    .then(function(responseJson) {
      return responseJson.myString
    })

    alert(fromServer);
}

if you go by the async/await approach i would suggest something more like this:

async function(){
    let response = await fetch('/fimlList')
    let responseJson = await response.json()
    let fromServer = responseJson.myString
    alert(fromServer)
}
Comments