In regards to this problem: How can I pass a value from the backend to a React frontend and use that value in the CSS for the frontend?, I have another issue.
Currently, I'm working on a project where a user talks into their mic and I take the transcript and score it, and based on that score I return it to the frontend and the scale moves accordingly. For some reason the backend of my project is not passing in the value I want it to, or my frontend just isn't processing it. When my backend passes a score of like 67, the scale in my frontend doesn't move from its initial starting position. But when I manually change what the score variable is in the front end (the score is a variable in the frontend which is where I store the score passed from the backend and it can be accessed by this.state.score), it works fine and the scale moves.
Here is my python backend code:
from flask import Flask, request
from flask_cors import CORS
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
# Processes and outputs score to screen
class ProcessData(Resource):
def processScores(self):
transcript = request.json
if transcript != '':
return 78
else:
print("Invalid input") # debug
return "Invalid Input"
# This is the function that sends the score to the frontend
def post(self):
x = self.processScores()
return x
api.add_resource(ProcessData, "/")
if __name__ == '__main__':
app.run(debug=True)
Here is my React code:
import React, { Component } from 'react';
class Product extends Component {
constructor() {
super();
this.state = {
// This is where the score is being saved
listening: false,
text: '',
score: '',
};
this.toggleListen = this.toggleListen.bind(this);
this.handleListen = this.handleListen.bind(this);
}
handleSending() {
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state.text),
};
fetch('http://127.0.0.1:5000/', options)
.then((response) => response.text())
.then((json) => this.setState({ score: json }));
this.setState({ text: '' });
}
render() {
return (
<div className="scale-container">
<div className="bar">
<div className="arrow-up" style={{ left: `${this.state.score}%` }}></div>
<span></span>
</div>
</div>
</div>
);
}
}
export default Product;
Does anyone know why this happens?