0

I'm trying to make a sidebar menu without lib and I got a problem.

I have a function used for setState, but it only works with JSX in return, when I render the menu and pass this function, it is run but setState not working in it.

Hear is my code:

export default function DropdownSideMenu(props) {
    const [state, setState] = useState({});

    const renderDropdownMenu = (data) => {
        return data.map((item) => {
            if (item.child.length >= 1) {
                return (
                    //THIS IS NOT WORKING, doSomeThing run but state not change.
                    <li key={item.id} onClick={() => doSomeThing(item.value)}>
                        <NavLink to={item.link}>{v[item.name]}</NavLink>
                        <ul>{renderDropdownMenu(item.child)}</ul>
                    </li>
                );
            }

            return (
                <li key={item.id}>
                    <NavLink to={item.link}>{v[item.name]}</NavLink>
                </li>
            );
        });
    };

    const doSomeThing = (value) => {
        console.log(value);
        setState(value);
    };

    return (
        <ul>
            {renderDropdownMenu(props.data)}

            {/* THIS IS WORKING, doSomeThing run well */}
            <li onClick={() => doSomeThing(value)}>
                <NavLink to="/">Test</NavLink>
            </li>
        </ul>
    );
}

UPDATE: Problem-solve I found a big mistake in the project, when project building, I make a Layout component and PUT IT INTO CONTAINER COMPONENT, this is the wrong way because when we struggle Sidebar in Layout component Router will re-render the container and make Layout re-render so Sidebar can not make action setState.

I FIXED BY PUT LAYOUT INTO APP COMPONENT and WRAP ALL CONTAINER INSIDE LAYOUT COMPONENT, it works fine.

P/s: If someone see another mistake, please mention it in the comments. Thanks you so much.

PS-PARSA
  • 932
  • 5
  • 15
Cyan Coder
  • 87
  • 7
  • Where is the value defined in onclick method? Do you want to pass event in callback? And How did you know the setState is not working, probably you are passing same value everytime – Vivek Kumar Mar 03 '21 at 09:14
  • What is `props.data`? How are you verifying/validating that state isn't being updated? It doesn't appear that `state` is even used in your example snippet. – Drew Reese Mar 03 '21 at 09:46
  • state is not being used, there is no v object in renderdropdown, there is no variable declaration or value assigned to value passed to doSomeThing. There are many pieces missing. – tarzen chugh Mar 03 '21 at 09:56
  • @VivekKumar i check console.log(state) before and after run setState in doSomething() so i sure (90%) it not run when we click item render by renderDropdownMenu – Cyan Coder Mar 03 '21 at 09:58
  • @DrewReese props.data is a fixed data like data = [ {name: "A", child: [{name: "C"} ] }, {name: "B", child: [] }] – Cyan Coder Mar 03 '21 at 09:58

0 Answers0