jamesscaggs
jamesscaggs

Reputation: 563

Express/React promise stalled

I have an Express backend server on port 5000 and react front end running on port 3000. I am trying to fetch some data from express post route and return it to front end but my Promise never resolves. It always ends up as "stalled".

util.inspect(messageList) shows my array on server console but my Promise on the front end never resolves.

I'm fetching some data server side on ComponentDidMount like below:

class Conversation extends React.Component {
  state = {
    conversations: [],
    messages: [],
    error: null,
    loading: true,
    input: '',
    owner: 'Unassigned'
  }

  componentDidMount() {
    const { match } = this.props
    const { conversationId } = match.params
    // Make a POST request to our server and pass the conversationId
    this.getMessages(conversationId)
  }

  getMessages(conversationId) {
    return fetch('/search-conversation', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ conversation: conversationId })
    })
      .then(res => res.json())
      .then((messages) => this.setState({ messages }))
  }

Server Side:

app.post('/search-conversation', (req, res) => {
    conversationId = req.body.conversation

    if (!conversationId) {
      res.send('/error');
    } else {
      console.log(`Success, conv id is ${conversationId}`);
    }
    // call function to go get messages from API
    console.log(`fetching messages for ${conversationId}`)
    return fetch(endpoint)
      .then((res) => res.json())
      .then(({ data }) => data)
      .then((data) => {
        const messageList = data[0].messages.data
        return messageList
      })
      .then((messageList) => console.log(util.inspect(messageList)))
      .catch(error => console.error(`Error: ${error}`))
  });

Any ideas are appreciated, thanks in advance.

Upvotes: 0

Views: 511

Answers (1)

antonku
antonku

Reputation: 7685

You are missing res.json() call on the server side that will send response to the client:

app.post('/search-conversation', (req, res) => {
  conversationId = req.body.conversation

  if (!conversationId) {
    res.send('/error');
  } else {
    console.log(`Success, conv id is ${conversationId}`);
  }
  // call function to go get messages from API
  console.log(`fetching messages for ${conversationId}`)
  return fetch(endpoint)
    .then((res) => res.json())
    .then(({ data }) => data)
    .then((data) => {
      const messageList = data[0].messages.data
      res.json(messageList)                         // <-- sending response
    })
    .catch(error => console.error(`Error: ${error}`))
});

Upvotes: 5

Related Questions