0

I have a react component that gets data from an API end point so that it can render some HTML.

I know that the call to the API works becuase I can out put the response in console.log(). However when I call the set function defined in the Use State so that I can set the state object when I console.log() that value it is empty.

This is my first react project so I may be missing something every fundamental, can only exaplain whats going on here?

This is the code so far:

function RenderCmsComponents() {
    const location = useLocation();

    const [componentItems, setCmsComponents] = useState([]);

    const getComponents = async () => {
        const componentList = await API.fetchPageComponents(location.pathname);
        setCmsComponents(componentList.CmsComponents);

        console.log(componentList.CmsComponents); //Works
        console.log(componentItems); // this is Empty, why?
    };

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


    return (
        <div>
            <p> Render CMS Components for `{location.pathname}`</p>
        </div>
    );
}
export default RenderCmsComponents;
Ayo Adesina
  • 2,231
  • 3
  • 37
  • 71
  • 1
    It's not available until the next render. Move it outside of that function, or add another useEffect with a dependency of that state variable and you'll see it change. – Joel Hager Feb 24 '22 at 07:18
  • @JoelHager - I'm very green to react can you answer the question with an exmaple? – Ayo Adesina Feb 24 '22 at 07:20
  • 1
    @JoelHager as @Ayo Adesina suggested said just create a new `useEffect` hook and in the dependency array add `componentItems`, once the state updates that `useEffect` block will be executed and then you can console log the fresh value, One thing you need to keep in mind is that `setCmsComponents` is async operation hence you don't immediately get the updated value after console.log(); – Mob_Abominator Feb 24 '22 at 08:35

0 Answers0