Home > front end >  I try to display api data but nothing comes out, not even an error on React
I try to display api data but nothing comes out, not even an error on React

Time:03-01

I'm slowly understanding the services and fetch with React but when I try to show something, it shows me absolutely nothing. I put the code in case someone can help me. Maybe I have to look at how to work with JSON, I don't know.

let datosApi = [];

const recogerDatos = () => {
    let json = "https://jsonplaceholder.typicode.com/albums";
    let miApi = "http://localhost/dsw/api/";
    fetch(json)
        .then(data => data.json())
        .then(info => {
            console.log(info);
            this.datosApi = info;
        })
}

function Services() {
    return (
        <>
            {datosApi.map(datos => (
                <p>{datos.title}</p>
            ))}
        </>
    );

}
export default Services;

JSON data appears in https://jsonplaceholder.typicode.com/albums

CodePudding user response:

I think your example is missing something or you've not done it.

Basically there's a few things wrong:

  1. recogerDatos is never being called
  2. datosApi is not declared, and even if it was, it's not stateful, thus won't cause a re-render of your items.

I've created a working sandbox here that shows it working, and the code is below:

const [result, setResult] = useState([]);
const recogerDatos = () => {
  let json = "https://jsonplaceholder.typicode.com/albums";
  fetch(json)
    .then((data) => data.json())
    .then((info) => {
      console.log(info);
      setResult(info);
    });
};

useEffect(() => {
  recogerDatos();
}, []);

return (
  <div className="App">
    {result.length > 0 && result.map((datos) => <p>{datos.title}</p>)}
  </div>
);

The recogerDatos function is called on page load (see useEffect), and the result is updated when the fetch is successful. This causes a re-render and the items are shown.

CodePudding user response:

You are displaying data from your list

let datosApi = [];

However it does not seem like you are populating your list with data from the API since the method recogerDatos() is never being called.

CodePudding user response:

From your code it seems like you're missing some core React patterns like state management and the components lifecycle. Since React re-renders components a lot you want to store things like fetched data into state to avoid them constantly reset to their initial value. And when you want to fetch the data you usually don't want to do it at each re-render (that would cause A LOT of fetching), instead you usually want to trigger it based on different events, for example when component (that will be used to show this data) is mounted. Such things are usually using the components lifecycle methods / useEffect hooks to ensure that they happen at the right point in time. I recommend you to go into React documentation and study the basics a bit more so you can understand the main concepts when you're coding, but here's a quick sandbox with an example of how you could get the desired effect in React: https://codesandbox.io/s/beautiful-frost-on9wmn?file=/src/App.js

  • Related