0

I want to set filtredMenu with items of full "menu" data by useEffect but when I console.log it, it gives null. When I do console.log(menu), it works without a problem, I see all menu items in the console. I will filter the filtredMenu by category buttons later. What am I doing wrong?

This is my document:

import { useContext, useEffect, useState } from "react";
import MenuContext from "../context/MenuContext";


function Menu() {

    const { menu, setMenu } = useContext(MenuContext);
    const [filtredMenu, setFiltredMenu] = useState(null);

    useEffect(() => {
        setFiltredMenu(menu);
        console.log(filtredMenu)
    }, []);

    function handleMenu(e) {
        e.target.value !== "all"
            ? setFiltredMenu(menu.filter(item => item.category === e.target.value))
            : setFiltredMenu(menu);
    }

    return (

        <>
            {/* {filtredMenu.map((item) => (
                    <>
                        <button key={item.id} value={item.category} onClick={handleMenu}>
                            {item.category}
                        </button>
                    </>
                ))} */}

            {menu.map((item) =>
                <div key={item.id}>
                    <div>
                        {item.title}
                    </div>
                    <div>
                        {item.category}
                    </div>
                    <div>
                        {item.price}
                    </div>
                    <div>
                        {item.desc}
                    </div>
                    <img src={item.src} alt="image" />
                </div>
            )}
        </>

    )
}

export default Menu

Thank you.

ozgur
  • 17
  • 5

1 Answers1

-1

This is because React's setState functions are async, you won't see the state change right away. If you would wait a second you would see the value change.

Charlie Araya
  • 430
  • 4
  • 9
  • 1
    Doh! You're right (and I wrote a whole answer after failing to read the code correctly). Which makes this an **often**-repeated duplicate of [this](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately). Please flag duplicates rather than posting answers to them. – T.J. Crowder Apr 22 '22 at 07:55
  • 1
    *Technically* the state update function is synchronous. It only enqueues an update that is asynchronously processed later. It doesn't return a Promise and can't be `await`ed. And I agree with T.J., duplicate questions should be marked as such when possible. – Drew Reese Apr 22 '22 at 07:57