Home > Software design >  React doesn't update data for loops
React doesn't update data for loops

Time:12-12

I've this problem with React:

<div className="container">
                <div className="row">
                    {servers.database?.map((server, index) => (
                        <div className="col">

                            <div className="card" style={{ width: "18rem", backgroundColor: "#101114", color: "white", marginTop: "80px", borderRadius: "15px", boxShadow: "4px 3px 5px 0px #7335fb" }}>
                                <img src="https://cdn.discordapp.com/icons/843104500713127946/a_91371d39bec9e454d0f4ccacbfaea9f8.gif?size=512" className="card-img-top" alt="Icona server" style={{ borderRadius: "50%", width: "96px", marginLeft: "20px", marginTop: "60px" }} />
                                <div className="card-body">
                                    <h5 className="card-title">{servers.bot?[index].name || "Errore!"}</h5><br />
                                    <p className="card-text">{server.shortDescription}</p><br />
                                    <a href="#" className="btn" style={{ backgroundColor: "#5316d9", color: "white" }}>Entra</a>
                                    <a href="#" className="btn" style={{ marginLeft: "10px", backgroundColor: "#5316d9", color: "white" }}>Visita</a>
                                    <br />
                                </div>
                            </div>

                        </div>
                    ))}
                </div>
            </div>
    </div>

I have this code.
Initially the servers is empty, so it doesn't load anything, and this is fine, but, when I update that object, I don't see any change in the page.
This is the code that I use for update the object:

    async function getServers() {

        console.log("ready")

        const response = await fetch('http://localhost:3000/server/servers').then(res => res.json())

        setServers(response);

        console.log(servers);
    }

I'm sure that the object is updated with necessary data.

useEffect that run the function:

    useEffect(() => {
        getServers();
        import('bootstrap/dist/js/bootstrap');
        WebFont.load({
            google: {
                families: [ 'Karla:600', 'sans-serif' ]
            }
        });
    }, []);

How I can fix that?
Thanks in advance and sorry for bad english.

CodePudding user response:

Here I have added an extra check for checking whether the servers is returning undefined or not

import { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [servers, setServers] = useState();

  const getServers = async () => {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts").then(res => res.json());

    setServers(response);

  }

  useEffect(() => {
    getServers();
  }, []);
  return (
    <div className="App">
      <div className="container">
        <div className="row">
          {servers !== undefined &&
            servers.map((server, index) => (
              <div className="col" key={index}>
                <p>{server.title}</p>
              </div>
            ))}
        </div>
      </div>
    </div>
  );
}

you can also check here

CodePudding user response:

The issue could be you are never calling getServers. You can do this by using the useEffect() hook. This will call the function once when the component is first rendered.

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

CodePudding user response:

the render function in React works faster than useEffect, so it will first render the page with

servers = []

and then it will update with 'setServers' - if that's a state variable it should work.

is it a state variable?

  • Related