-2

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;
Andy
  • 156
  • 1
  • 12
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Jared Smith Nov 03 '21 at 13:33
  • Also note that you need to wrap in useEffect and update state with useState per the upvoted answers. – Jared Smith Nov 03 '21 at 13:34

2 Answers2

2

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);
        }
      })()

    }, [])
    
SoGoddamnUgly
  • 706
  • 4
  • 9
  • Note that this will fetch the data again on every single render. You might want to add a dependency array to `useEffect` – Jared Smith Nov 03 '21 at 13:36
  • When I do this, I get a bunch of compilation errors saying that data, setData, and useState are not defined. Do I need to import anything else? I dont believe I have to – vynabhnnqwxleicntw Nov 03 '21 at 13:43
  • oh... import useState and React aswell. Let me edit it. – SoGoddamnUgly Nov 03 '21 at 13:44
  • i also forgot const [data, setData]. – SoGoddamnUgly Nov 03 '21 at 13:47
  • Thank you! I believe this works, just right now I am getting the error message on my webpage console "Access to XMLHttpRequest at 'http://localhost:8080/run' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." This seems to be a relatively common issue so I'll work on it a little bit first. – vynabhnnqwxleicntw Nov 03 '21 at 14:29
  • 2
    That is a server problem. I'm glad it helped. – SoGoddamnUgly Nov 03 '21 at 14:46
-1

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(",");
    });
k-wasilewski
  • 3,943
  • 4
  • 12
  • 29
  • You can't do arbitrary side-effects (like an axios request) in a React function component. See the other answers. – Jared Smith Nov 03 '21 at 13:35
  • So he can split that into multiple functions, my answer was only to give a sense of `async`ivity.. – k-wasilewski Nov 03 '21 at 13:49
  • Except that the OP is clearly an inexperienced dev, and is going to copy-paste your answer into their React function component, and then not understand why it doesn't work or works but only once in awhile. – Jared Smith Nov 03 '21 at 13:50