Octavian
Octavian

Reputation: 673

Set the data in React Context from asynchronous API call

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?

Upvotes: 30

Views: 42180

Answers (1)

Eslam Abu Hugair
Eslam Abu Hugair

Reputation: 1208

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>
    )
}

Upvotes: 36

Related Questions