I am trying to make an http request to my backend server (run on java springboot) with my React-based frontnend, which returns a string that I want to parse and assign to values. From what I have seen on the syntax pages, I want to believe that I am calling the request correctly. My error message mentions "Cannot read properties of undefined (reading 'split')", which I think means that split() is not a valid operation for js or React? Does anyone know what is the correct way to this?
import React from 'react';
import './App.css';
import Exchange from './Exchange'
import Recommendations from './Recommendations';
import axios from "axios";
function Middle(){
const response = axios.get("http://localhost:8080/run");
const data = response.data;
const dataArr = data.split(",");
return (
<div className = 'Middle'>
<h1>{data}</h1>
<Exchange name = "Coinbase" btcBuy = {dataArr[1]} btcSell = "" ethBuy = "" ethSell = ""/>
<Exchange name = "Binance" btcBuy = "" btcSell = "" ethBuy = "" ethSell = ""/>
<Recommendations/>
</div>
);
};
export default Middle;
It means that the data variable is not a string. Also you need to use useEffect if you want to fetch data.
import React, { useState, useEffect } from "react";
function Middle(){
const [data, setData] = useState([]);
useEffect(() => {
(async () => {
try {
const response = await axios.get("http://localhost:8080/run");
const data = response.data;
setData(data); // use split if you have to, I dont think you need that.
} catch(err) {
console.error(err);
}
})()
}, [])
Actually you do not read the response properly, as it is an asynchronous operation and your response is undefined at the time you make operations on it sequentially.
You have to place your code in the body of .then, like this:
let dataArr = [];
axios.get("http://localhost:8080/run")
.then(response => {
const data = response.data;
dataArr = data.split(",");
});
It is because data is not set yet . axios returns promise you have to use await for that purpose. and you shouldnt call api like that useeffect is built for that purpose
import React from 'react';
import './App.css';
import Exchange from './Exchange'
import Recommendations from './Recommendations';
import axios from "axios";
function Middle(){
const [data,setData] = React.useState(null)
useEffect(()=>{
//will get rid of warning of memory leak
let mounted = false
if(!mounted){
axios.get("http://localhost:8080/run")
.then(data=>setData(data))
.catch(err=>//do something);
}
return ()=>mounted= true
},[])
return (
<div className = 'Middle'>
<h1>{data}</h1>
<Exchange name = "Coinbase" btcBuy = {dataArr[1]} btcSell = "" ethBuy = "" ethSell = ""/>
<Exchange name = "Binance" btcBuy = "" btcSell = "" ethBuy = "" ethSell = ""/>
<Recommendations/>
</div>
);
};
export default Middle;