Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
User Data from DynamoDB is rendered too late when calling it

So I am trying to pull a users friendsList from a dynamoDB. I am using an GraphQL API to access my DB. In the commented out section of the code provided there I mention I have tried users[1].friends.map, which does return the correct friends list array, but users does not seem to get set until after the friends list has been rendered. How should I set up my code so the correct friends list (found in users) gets rendered the first time the page is rendered rather than after it gets updated??

const FriendsList = [
 {
    name: 'Name 1',

  },
  {
    name: 'Name 2',

  },
  {
    name: 'Name 3',

  }, 
  {
    name: 'Name 4',

  },
  {
    name: 'Name 5',

  },
  {
    name: 'Name 6',

  },
  
];
const Friends = (props) => {

  const [refreshing, setRefreshing] = React.useState(false);
  const [users, setUsers] = React.useState([]);
  const [formData, setFormData] = React.useState(initialFormState);

  React.useEffect(() => {
    fetchUserData();
   }, []);

  async function fetchUserData() {
    const userData = await API.graphql({ query: listUsers });
    setUsers(userData.data.listUsers.items);
  }


  //console.log(users);
    const renderFriendsList = (props) => {

    /* 
     *Here I want to have something like...
     * return users[1].friends.map((item, i) => {
     * so I can iterate through the friends list 
     */
    return FriendsList.map ((item, i) => {
        return (
          <View style={{ paddingLeft: scale(10), paddingRight: scale(10) }}>
            <View
              style={{
                backgroundColor: '#d1cfcf',
                width: scale(330),
                height: scale(85),
                borderRadius: scale(10),
                flexDirection: 'row',
                borderColor: '#8f8a8a',
                borderBottomWidth: 1,
              }}>

              <View>
                <Text style={{ fontSize: 15 }}>{item.name}</Text>
              </View>
            </View>
          </View>
        );
    
    });
  };

    return (
      <View style={{}}>
          <View style={{ marginTop: scale(5) }}>
            {renderFriendsList()}
          </View>
      </View>
    );
  }

fetchUserData() should set users to the user data, but when I call users before the first time it renders, users is still undefined. If the application is running and has rendered the friends list from friendsList, and then I change it to users1.friends on the fly, it works, but that is obviously is an issue because it does not render correctly the first time. I use the React.useEffect() and I figured that would call fetchUserData() when the page is rendered.

Here is the output I am getting when I console.log(users.result) Here is the output I am getting when I console.log(users.result)

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

useEffect with an empty array as argument gets called after the initial render, this is normal behaviour.

Usually when you want to render state related to an api call, you would store in the form of something like this:

const defaultState = { loading: false, result: null, error: null };
const [users, setUsers] = useState(defaultState); 

Therefore you can do something like this:

async function fetchUserData() {
    setUsers({ ...defaultState, loading: true });
    try {
        const userData = await API.graphql({ query: listUsers });
        setUsers({ ...defaultState, result: userData.data.listUsers.items});
    } catch (e) {
        setUsers({ ...defaultState, error: e.message });
    };
}

Since you're making a remote call it makes sense to show a spinner during the load time, rather than immediately rendering the collection.
Therefore you can use the loading property on the state object for this purpose.

Of course there are other techniques where you immediately make the ajax call at the server, and either push them as json to the client immediately, or just render the html from the server.

Edit: Based on the current solution you can do:

... 
return (
    <>
        { loading && <>loading...</> }
        {
            !loading
            && result 
            && <FriendList result={ result } /> // map now that the results are available 
        }
    </>
)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda