Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading