Search code examples
reactjsreact-state-managementreact-state

After setting state elements are not rendered in the browser


I am trying to fetch some data from an API and render it in my browser. My code is as below:

import React from 'react'
import {Col, Container, Row} from "react-bootstrap";
import {getTests} from "../services/getTests.setvice";
import TestRow from "../components/testRow.component";

class HomeScreen extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            testList: []
        }
    }

    componentDidMount = async () => {
        const list = await getTests();
        this.setState({testList: [...list]});
    };


    render() {
        console.log(this.state.testList);
        return (
            <Container style={{maxWidth: '100%'}}>
                <Row>{this.testList ? this.testList.length : 0}</Row>
                <Row style={{height: 100}}>
                    <Col md={3}>{!this.testList ? <div>No test found</div> : this.testList.map((test) => {
                        return <TestRow>{test.attributes.name}</TestRow>
                    })}</Col>
                    <Col md={9}></Col>
                </Row>
            </Container>
        )
    }
}

export default HomeScreen;

The issue is that even though the list is printed successfully in the console. It is not being rendered on the browser. Please help me identify what I am doing wrong. My console log is as in the screenshot below: enter image description here


Solution

  • You are referring to this.testList in your Col component, instead of this.state.testList. this.testList doesn't exist, so it renders nothing.