React component no rendering

  javascript, preview, reactjs, url

So We have an HTML page

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>The Great: Page of Life</title>
</head>

<body>
    <div style="width: 100%;">
        <div id="shopping-cart-container": 100%;"></div>
        <div id="preferences-container"></div>
    </div>
    <div style="clear:both"></div>
</body>

</html>

In the same folder, we have an index.jsx

import React from 'react';
import { render } from 'react-dom';
import { MainShoppingCartComponent } from './ShoppingCart.jsx';
import { MainComponent } from '../Popup/Popup.jsx';
import './index.css';

render(<MainShoppingCartComponent />, window.document.querySelector('#shopping-cart-container')
);
render(<MainComponent />, window.document.querySelector('#preferences-container'));

MainComponent renders no hassle and interacts as expected.
But MainShoppingCartComponent does not render at all. When I try to print out different steps along the way I see it gets stuck in the componentDidMount function.

import React from 'react';
import './ShoppingCart.css';
import { ReactTinyLink } from 'react-tiny-link'

export class MainShoppingCartComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            itemsInCart: {},
        };
    }

componentDidMount = () => {
    let { itemsInCart } = this.state.itemsInCart;
    chrome.storage.sync.get(
        "shopping_Cart",
        function (result) {
            console.log("what was returned from local storage", result);
            console.log("what the current state is", itemsInCart);

            this.setState({ itemsInCart: result }, () => { console.log("woohoo") });
            console.log(this.state.itemsInCart)
        }
    );
}

The console output for this section is enter image description here
So the state appears to remain undefined after I try to set it.

at the end of MainShoppingCartComponent when I try to render something out

render() {
    let itemsInCart = this.state.itemsInCart;
    console.log("itemsInCart", itemsInCart);
    return (
        < div className='cart-class' >
            <div id="cart_container">
                {Object.values(this.state.itemsInCart).map(v => <CartItemComponent url={v}/>}
            </div>
            <span id="pop-button" className="waves-effect btn" title="Click to empty cart" onClick={this.changeDisplay}></span>
        </div>
    );
}

The output from the console.log in the render is the original state enter image description here as opposed to undefined. Any pointers really appreciated

Source: Ask Javascript Questions

LEAVE A COMMENT