1

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;
5
  • Use console.log(child) to see what you got. It seems like one of your values is an object Commented Dec 3, 2022 at 12:42
  • Looks like and attempt to render an plan object, either its in the reutrn <>{data && data.length > 0 && child }</> or in the JSX markup in one of the properties el.stars , looks like { child } is considered as an object Commented Dec 3, 2022 at 12:48
  • Does the switch statement need to be inside a useEffect to fetch data Commented Dec 3, 2022 at 12:51
  • @Azzy No it does work outside of a useEffect, Is it conventionally supposed to be in one ? Commented Dec 3, 2022 at 12:57
  • @DKWebservices, initial fetch is generally done inside a useEffect, nor without any checks it might occur on very render cycle Commented Dec 3, 2022 at 13:01

2 Answers 2

2

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 }</>;
Sign up to request clarification or add additional context in comments.

1 Comment

This was definitely the problem, thanks a lot
1

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}</>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.