Search code examples
reactjstsx

values inside foreach pushes undefined?


So I am working with a tsx file and I tried to push some html into a variable with options in it that takes their value from foreach item and so far so good but then I try to push them into some array and use it in my state in order to do the right thing for react it pushes undefined. ı am confused how it gives undefined when I try to push it into array and it gives value when I try to push it into html element

provider.getItems().then((items:any[]) => { 
        items.forEach((item) => {
            this.categoryOptItems.push(item.Title);
            this.categoryOpts.push(<option value={item.Title}>{item.Title}</option>)    
        })
        this.setState({categories: 
            this.categoryOptItems
        }) 
    })

Solution

  • I found my solution but not sure if it is the best way though.

    This is in componentDidMount

        provider.getItems().then((items:any[]) => { 
            items.forEach((item) => {
                categoryOptItems.push(item.Title);
            })
            this.setState({categories: 
                categoryOptItems
            })
        })
    

    This is the function

    options() {
        var categories = this.state.categories;
        const html:any = [];
        for (var i = 0; i < this.state.categories.length; i++) {
            html.push(<option value={i+1}>{categories[i]}</option>);
        }
        return html;        
    }