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?
Now, because React Tracked is a wrapper around React Hooks and Context, it doesn't support async actions natively. This post shows some examples how to handle async actions.
Introduction to React-Async React Async is a promise-based library that offers a declarative API to make API calls. It provides a React component and a Hook for declarative promise resolution and data fetching. Source: https://www.npmjs.com/package/react-async.
try to use useContext
its cleaner and try not to use the async inside the useEffect!
their related issues
import React, { useState,useEffect,useContext } from "react";
import { callAffiliateApi } from "./services/affiliateService/transactionContext";
const Context = React.createContext({});
const AffiliateContext = init => useContext(Context);
export const AffiliateProvider = ({children}) => {
const [data, setData] = useState(null);
const [loading,setLoading]=useState(false);
const getAffiliates = async ()=>{
setLoading(true)
const newText = await callAffiliateApi();
setData(newText)
setLoading(false)
}
useEffect(()=> {
getAffiliates()
},[])
return (
<AffiliateContext.Provider value={{loading,list:data}}>
{children}
</AffiliateContext.Provider>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With