Home > database >  Why does my function run before componentDidMount
Why does my function run before componentDidMount

Time:11-17

I am trying to create a menu using @szhsin/react-menu. I am getting an error that element is undefined. componentDidMount has not run yet (Nothing in the Console Log). I would have thought my if (this.state.Categories == null) would catch before AddMenu is ever called.

import Config from 'config';
import { Nav, NavItem, Dropdown, DropdownItem, DropdownToggle, DropdownMenu, NavLink } from 'reactstrap';
import { Menu, MenuItem, MenuButton, SubMenu } from '@szhsin/react-menu';
import '@szhsin/react-menu/dist/index.css';
import '@szhsin/react-menu/dist/transitions/slide.css';
import React, { useState } from 'react';

class GetCategories extends React.Component {
    constructor() {
        super();
        this.toggle = this.toggle.bind(this);
        this.state = {
            name: 'React',
            apiData: [],
            isOpen: false,
        };
    }    

    componentDidMount() {
        console.log('app mounted');
        fetch(Config.apiUrl   "/api/Items/GetCategories")
            .then(data => data.json())
            .then(data => this.setState({ Categories: data }, () => console.log(data)));
    }    

    render() {
        var catList = this.state.Categories;
        let categoriesStyled = [];

        function AddMenu(category) {
            if (category.children.length !== 0) {
                console.log(category)
                categoriesStyled.push(<SubMenu label={category.name}>);
                category.children.forEach(element => AddMenu(element) );
                categoriesStyled.push(</SubMenu>);
            }
            else {
                categoriesStyled.push(<MenuItem>{category.name}</MenuItem>);
            }
        }


        if (this.state.Categories == null) {
            console.log("NULL");
            return (
                <div>
                    <h1>{/*ERROR*/}</h1>
                </div>
            );
        }
        else {

            for (let i = 0; i < catList.length; i  ) {
                if (catList[i].name !== undefined) {
                    AddMenu(catList[i]);
                }
            }            

            return (
                <div>                    
                    <Menu direction={'bottom'} menuButton={<MenuButton>Shop</MenuButton>} transition>
                        <>
                            {categoriesStyled}
                        </>
                    </Menu>                        
                </div>
            );
        }

    }
}
export default GetCategories;

I am sure this is my dumb mistake but I just don't see it yet. Any help will be greatly appreciated.

UPDATE

My json data returned:

[
  {
    "categoryId": 3091,
    "parentId": 0,
    "name": "Concrete Services",
    "title": "Concrete Services",
    "description": "Concrete Services",
    "keywords": "Concrete, perfect polish",
    "pageContent": "<span style=\"color:Blue; border-color:Blue; font-weight:bold; font-size:18pt;\">Concrete Services<br/><br/><span style=\"color:#ff6600; border-color:#ff6600; font-size:14pt;\">Perfect Polish provides a wide range of services to fit any need.&edsp;&edsp;Either repair of existing floors, or installation of completely new floors.</span><br/></span>",
    "bannerGroupId": 0,
    "inactive": false,
    "issitecategory": false,
    "sortOrder": null,
    "children": [
      {
        "categoryId": 3092,
        "parentId": 3091,
        "name": "Concrete Polishing",
        "title": "Concrete Polishing",
        "description": "Concrete Polishing",
        "keywords": "polish, polishing",
        "pageContent": "<span style=\"color:Red; border-color:Red; font-style:italic; font-weight:bold; font-size:16pt;\">Concrete Polishing</span><br/><br/>Perfect Polish is the industry leader specializing in polished concrete floors. Our company has performed work across the country for all types of industrial, commercial, and retail facilities. <br/><br/>We perform new construction, facility improvement projects, and provide assistance from pour to completion to insure each project meets our customer expectations.",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3094,
        "parentId": 3091,
        "name": "Repair and Restoration",
        "title": "Repair and Restoration",
        "description": "Repair and Restoration of existing Concrete floors",
        "keywords": "repair, restore, restoration",
        "pageContent": "<span style=\"color:Navy; border-color:Navy; font-weight:bold;\">Repair &amp; Restoration</span><br/>Perfect Polish has years of experience improving facilities with damaged floors. Our team will assess your floors and determine the amount of repair required to bring your floor back to life. Repair and restoration can include cracked concrete, pop-outs, spalling, joint damage, coating removal and more.",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3093,
        "parentId": 3091,
        "name": "Resinous Flooring",
        "title": "Resinous Flooring",
        "description": "Resinous Flooring",
        "keywords": "resinous, resin",
        "pageContent": "<span style=\"color:#ff6600; border-color:#ff6600; font-size:14pt;\">Resinous Flooring</span><br/><br/>Perfect Polish provides resinous flooring services for customers with new and existing facilities across the United States. We offer a wide range of resinous flooring options including <span style=\"font-style:italic;text-decoration: underline;\">epoxy, urethane, and acrylic materials, decorative options, line striping, border painting, and more.</span>",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      }
    ]
  },
  {
    "categoryId": 1005,
    "parentId": 0,
    "name": "Electrics",
    "title": "Electrics",
    "description": "Electrics",
    "keywords": "Electrics",
    "pageContent": "Electrics <span style=\"color:#33cccc; border-color:#33cccc; font-weight:bold;\">- page of information</span>",
    "bannerGroupId": 0,
    "inactive": false,
    "issitecategory": false,
    "sortOrder": null,
    "children": [
      {
        "categoryId": 1006,
        "parentId": 1005,
        "name": "FloodLights",
        "title": "FloodLights",
        "description": "FloodLights",
        "keywords": "FloodLights",
        "pageContent": "FloodLights",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 1007,
        "parentId": 1005,
        "name": "Light",
        "title": "Lights",
        "description": "Lights",
        "keywords": "Lights",
        "pageContent": "Lights",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3095,
        "parentId": 1005,
        "name": "Motors",
        "title": "Electric Motors",
        "description": "Electric Motors",
        "keywords": "Electric Motors, Motors",
        "pageContent": "<span style=\"font-weight:bold;\">Electric Motors</span><span style=\"color:#33cccc; border-color:#33cccc; font-weight:bold;\">- Provided by Kinney Electric &amp; Power Transmission</span>",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      }
    ]
  },
  {
    "categoryId": 3056,
    "parentId": 0,
    "name": "Fasteners",
    "title": "Fasteners",
    "description": "Fasteners",
    "keywords": "Anchors, bolts, hardware, nails, nuts, pins, clips, rivets, rods, screws, sockets, clamps, hangers, washers",
    "pageContent": "<p style=\"text-align:Left;\"><span style=\"border-color:Red; font-weight:bold; font-size:12pt;\"><span style=\"color:Blue; border-color:Blue;\">FASTENERS</span><br/>Same Day Shipping On Bulk Industrial Fasteners</span><br/><span style=\"color:Blue; border-color:Blue; font-style:italic;\">The Fastener Superstore is your one stop shop for nuts,<span style=\"color:Red; border-color:Red;\"> bolts, washers, rivets, standoffs and mo</span>re! <br/>We have <span style=\"text-decoration: underline;\">everything</span> you need right here.&edsp;</span><br/>* 34,000  Distinct Parts<br/>* All Pricing Online<br/>* No Registration Required<br/>* Same Day Shipping on Most Orders<br/>* Order online, via phone, email or fax<br/>* Extended Customer Service Hours (7am-7pm CT)<br/>* Quotes Available for Larger <span style=\"color:#3366ff; border-color:#3366ff;\">Quantities</span></p>",
    "bannerGroupId": 0,
    "inactive": false,
    "issitecategory": false,
    "sortOrder": null,
    "children": [
      {
        "categoryId": 3057,
        "parentId": 3056,
        "name": "Bolts",
        "title": "Bolts",
        "description": "Bolts",
        "keywords": "Bolts, Carraige, Dowel, Hanger, Elevator",
        "pageContent": "<span style=\"font-style:italic; font-weight:bold;\">The quality of the bolt you use can determine the integrity of the entire structure</span> — whether it’s a building project or a piece of machinery. Builders and contractors looking to buy wholesale nuts and bolts know they can trust Fastener <span style=\"color:Red; border-color:Red;text-decoration: underline;\">SuperStore to have the most comprehensive selection. </span>We are known for providing only the highest quality fastener hardware specific to whatever your application may be. See our list of bolt products and some common uses below, as well as information about what Fastener SuperStore can do for you.",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3096,
        "parentId": 3056,
        "name": "MKT",
        "title": "MKT",
        "description": "MKT Fasteners",
        "keywords": "MKT",
        "pageContent": "",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      {
        "categoryId": 3069,
        "parentId": 3056,
        "name": "Nails",
        "title": "Nails",
        "description": "Nails",
        "keywords": "Nails",
        "pageContent": "",
        "bannerGroupId": 0,
        "inactive": false,
        "issitecategory": false,
        "sortOrder": null,
        "children": []
      },
      ...
      

CodePudding user response:

Two problems

  1. this.toggle is undefined so this.toggle = this.toggle.bind(this); is erroring
  2. You're pushing JSX elements into an array like you are building a string. They aren't strings. In fact you've created a single JSX element here that includes some things you think are code.
                categoriesStyled.push(<SubMenu label={category.name}>);
                category.children.forEach(element => AddMenu(element) );
                categoriesStyled.push(</SubMenu>);

<Submenu..> category.children.forEach(... </Submenu> is all one piece of jsx and there's actually only one push being called here not two.

It should be a single element with a child not a start / child / end element.

categoriesStyled.push(
    <SubMenu label={category.name}>
        {category.children.forEach(element => AddMenu(element)}
    </SubMenu>)

When I remove the this.toggle line and fix the push your code works fine.

CodePudding user response:

this.state.Categories is undefined not null. You should try if(!this.state.Categories) instead of if(this.state.Categories == null)

  • Related