Phil
Phil

Reputation: 949

UseEffect is empty in the beginning

I m traying to create a component using Hooks. Inside useEffect I call a function, but it dosen 't work. I think is because when the app starts the props is empty and in the second, when is full dosen 't call the function again.. WHY I m doing wrong? Thanks (sorry for my bad english)

this is the code:

import React, { useState, useEffect } from "react";

const fetchContent = async content => {
  console.log(content) // is empty in the first console, and full in the second.
  const data = [];

  for await (const item of content) {
     data.push({ componentName: item.nombre});
  }
  return data;
};

function ContentGroups(props) {
  const [contentResult, setResult] = useState([]);

   useEffect(() => {
     fetchContent(props.info).then(data => setResult(data));
     console.log(contentResult) // is empty in the first console, and full in the second.
  }, []);

  return (
    <React.Fragment>
       {contentResult.map((el, index) => {
        switch (el.componentName) {
          case "top":
            return <h1>soy un top words</h1>/*
        }
      })}
    </React.Fragment>
  );
}

Upvotes: 1

Views: 4264

Answers (2)

Julio Javier
Julio Javier

Reputation: 162

console.log prints before getting the result

useEffect(() => {
  fetchContent(props.info).then(data => {
    setResult(data);
    console.log(data);
  });
}, []);

Upvotes: 1

Dennis Vash
Dennis Vash

Reputation: 53884

Try adding a props dependency in your useEffect deps array:

useEffect(() => {
  fetchContent(props.info).then(data => setResult(data));
}, [props.info]);

Why your example not working?

First, you logging your data while setState is async, console.log(contentResult) will log the current state before the update.

Secondly, you run your useEffect with empty dep array which means you run it once on the component mount.

Upvotes: 1

Related Questions