I am trying to initialize a custom React context with data from back end, using a GET API request. However, the context is loaded before the API call finishe the data fetching.
What I've tried is to use a consumer to send data to the child component but I can only access the default value of the context which is set then the context is created.
Here is how I am trying to set my context data
import React, {useState,useEffect} from "react";
import {callAffiliateApi} from "./services/affiliateService/transactionContext";
export const AffiliateContext = React.createContext("Raaaaaaaaaaaa");
export const AffiliateProvider = ({children}) => {
const [data, setData] = useState(null);
useEffect(()=> {
async function fetchData() {
const newText = await callAffiliateApi();
setData(newText)
};fetchData()
},[])
console.log("Data in the context", data);
if(data != null){
return (
<AffiliateContext.Provider value={data}>
{children}
</AffiliateContext.Provider>
)}
else {
return (
<AffiliateContext.Provider value={"Loading..."}>
{children}
</AffiliateContext.Provider>)
}
}
And here is how I'm trying to access it in the child component
import {AffiliateContext} from "../../../../AffiliateContext";
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
text: this.props.text,
user: this.props.user,
}
}
render() {
return (
<AffiliateContext.Consumer>
{data =>
<div>
{data}
</div>}
</AffiliateContext.Consumer>
)
}
}
export default Profile;
However, the only thing that gets displayed in the page is "Raaaaaaa", the default value of the component. How can I make the child component wait until the data finishes fetching from the API request?