2

so I'm trying to call a simple backend service with react (FYI I don't know too much about react or javascript)


import React from 'react';
import logo from './logo.svg';
import './App.css';

const {EchoRequest, EchoResponse} = require('./proto/api_pb.js');
const {EchoServiceClient} = require('./proto/api_grpc_web_pb.js');
var echoService = new EchoServiceClient('http://localhost:8081');

function App() {
    var request = new EchoRequest();
    request.setMessage("Pew Pew Pew")
    let message = "initial value"
    echoService.echo(request, {}, function (err, response) {
        console.log(response.getMessage())
        message = response.getMessage()
    });
    return (
        <div className="App">
            <header className="App-header">
                <img src={logo} className="App-logo" alt="logo"/>
                <p>
                    {message}
                </p>
            </header>
        </div>
    );
}

export default App;

I'm trying to template the return value of message (which should have the value of echoService.echo's response) but the app keeps showing "initial value" instead of the actual response type, even though it shows in the console

I know this has to do with some asynchronous behaviour, but I don't know how to wait for the request to finish.

joshcarp
  • 21
  • 1

1 Answers1

0

Changing a value like this won't trigger a re-render, that's why in React you can use state. If you change the state your component will re-render. This don't happen because you don't use state which results in your component showing the default value.

Here is a little documentation about how state works: https://reactjs.org/docs/state-and-lifecycle.html

To solve your issue you can use a React hook like this:

import {useState} from 'react'
const [message, setMessage] = useState("initial value")

// Do some stuff here

setMessage(response.getMessage())

This code obviously won't work out of the box but it shows the basics.

Trisma
  • 735
  • 6
  • 19