sakib11
sakib11

Reputation: 536

data from React UseContext is undefined for a period

const [districtData] = useContext(DistrictDataContext);
    console.log(districtData); //undefined then available
    return (
        <Row>
            <Col md={{ span: 6, offset: 3 }} style={{ height: "50vh" }}>
                {" "}
                <GoogleMapReact
                    bootstrapURLKeys={{
                        key: "#",
                    }}
                    defaultCenter={{ lat:#, lng: #}}
                    defaultZoom={10}>
                    {districtData.map(function (item) {//undefined})}
                </GoogleMapReact>
            </Col>
        </Row>
    );

My react context data remains undefined for awhile when i try to console.log it. But it logs after short second but by that time my map higher order function has failed. I am not sure how to deal with this. I was thinking of using useEffect but the useEffect is already applied in the context provider to run on component did mount. I tried to remedy it by checking if the districtData is available at first like this:

{districtData && districtData.map(function (item) {
return <MarkerComponent details={item} />;
})}

This gives Expected an assignment or function call and instead saw an expression no-unused-expressions which is weird because Why is it expecting an assignment? Edit this was because i didn't return in map function. But the data is still unpresent. Why is the console.log undefined at first. Will that ever cause a problem?

Upvotes: 0

Views: 300

Answers (1)

Francesc Montserrat
Francesc Montserrat

Reputation: 349

{districtData && districtData.map(function (item) {
return <MarkerComponent details={item} />;
})}

Will try to render false in the case districtData is undefined, null etc. Could be replaced with an empty array.

{(districtData || []).map(function (item) {
return <MarkerComponent details={item} />;
})}

Expected an assignment or function call and instead saw an expression no-unused-expressions will go away with parenthesis:

{(districtData || []).map(function (item) {
return (<MarkerComponent details={item} />);
})}

Upvotes: 1

Related Questions