I am sure I am over complicating things, but I have a application that grabs user credentials at which point it performs a web auth to retrieve a sessionID. I take this session ID and save it in my App Context so that all the web components that need a sessionID can call the Context.
I am having a problem trying to figure out state in a manner that would allow me to wait for the SessionID to get populated before rendering the web components.
I have tried various conditional rendering techniques but apparently I am an idiot haha.
import React from "react";
import {Bar} from 'react-chartjs-2';
import Draggable from 'react-draggable';
import './FetchEndpoints.css'
import { AppContext } from "../../context/AppContext";
export default class FetchEndpoints extends React.Component {
static contextType = AppContext
state = {
loading: true,
dreturn: null,
render: false
};
async componentDidMount(){
const {session} = this.context
const url = "https://portal.local";
let headers = new Headers();
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
headers.set('session', session);
console.log(session)
const response = await fetch(url,{method:'POST',
headers: headers
});
const r_data = await response.json();;
this.setState({
loading: false,
chartData : {
datasets:[
{
label: 'Endpoints',
backgroundColor: [
'rgba(255,99,132,0.2)',
'rgba(54,162,235,0.2)',
'rgba(255,206,86,0.2)',
'rgba(75,192,192,0.2)'
],
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [r_data.info.data.total, r_data.info.data.unmanaged,r_data.info.data.managed,r_data.info.data.unmanageable]
}
]
}
})
}
render() {
if (this.state.loading) {
return( <h1>...loading</h1>)
}
return (
<Draggable
handle=".handle"
defaultPosition={{x: 0, y: 0}}
position={null}
grid={[25, 25]}
scale={1}
onStart={this.handleStart}
onDrag={this.handleDrag}
onStop={this.handleStop}>
<div className="handle">
<div>
<div className="EndpointBox">
<div className = 'chart'>
<Bar
data={this.state.chartData}
width={600}
height={200}
options={{
maintainAspectRatio: false,
title: {
display:true,
text:'Discovered Interfaces',
fontSize:15
},
legend:{
display:false
}
}}
/>
</div>
</div>
</div>
</div>
</Draggable>
);
}
}```
The session from AppContext renders after the above has already ran. I would like to set something up so that it would if session is null wait for session to not be null.
You should probably move the logic contained in componentDidMount
to a separate function - fetchCartData
for example.
Then, you could implement something like this:
async componentDidMount() {
if(this.context.session !== null) {
this.fetchChartData();
};
}
async componentDidUpdate() {
if(this.context.session !== null) {
this.fetchChartData();
};
}