Home > Software design >  REACT AXIOS Parsing Json
REACT AXIOS Parsing Json

Time:12-03

I am new to react, so if I am doing anything outside of the problem wrong please tell me also.

I'm trying to map my json response into a table, I can collect the data into an object array, but I am receiving this error : enter image description here

Here is the components code:

import axios from "axios";

function FilmTableRows(props) {
  const dataFormat = props.dataFormat;
  const [data, setData] = useState([]);
  const baseURL = "http://localhost:8080/FilmRestful/filmapi";

  const getJson = () => {
    let config = {
      headers: {
        "data-type": "json",
        "Content-type": "application/json",
      },
    };
    axios
      .get(baseURL, config)
      .then((res) => {
        const resData = res.data;
        setData(resData);
      })
      .catch((err) => {});
  };

  switch (dataFormat.value) {
    case "json":
      getJson();
      console.log(data);
      break;
    case "xml":
      getXML();
      console.log(data);
      break;
    default:
      getString();
      console.log(data);
  }

  const child = data.map((el) => {
    return (
      <tr key={el.id}>
        <td>{el.title}</td>
        <td>{el.year}</td>
        <td>{el.director}</td>
        <td>{el.stars}</td>
        <td>{el.review}</td>
      </tr>
    );
  });

  return <>{data && data.length > 0 && { child }}</>;
}

export default FilmTableRows;

CodePudding user response:

The error is caused because you wrap child with {} when you render it, which turns it into an object with an array variable. Try removing them like so:

return <>{data && data.length > 0 && child }</>;

CodePudding user response:

In your case child doesn't need to be wrapped inside {} because it is array of HTML Elements.

also you don't need to check data.length in order to map your array ,

that's bacause array with 0 length does not render anything automatically.

just change your render to following code :

return <>{data && child}</>
  • Related