0

I am using context api , but when I fetch data from backend and try to send it to child component , it doesnt seem to work , console logs an empty array .

import {MyApiUrl} from './services/httpService'


export const GlobalState = createContext()

export const DataProvider = ({children}) =>{

    const [categories, setCategories] = useState([])


    const getCategories = async () =>{
        const res = await http.get(MyApiUrl+'/api/jobCategory');
        setCategories({categories:res.data})
    }

useEffect( ()=>{

    getCategories()

},[])

    const mystate = {
      
        categoriesAPI: categories

    
    }
  
   


console.log(categories)
    return (
        <GlobalState.Provider value={mystate}>
            {children}
        </GlobalState.Provider>
    )
}

now in one of the child components which is class


static contextType = GlobalState

  async  componentDidMount(){
   
   
    const mystate = this.context
console.log(mystate,'hey')        //  >>>>>>> ITS NOT CONSOLE LOGGING THE VALUE HERE 

}
  • Try `setCategories(res.data)` in `getCategories` – Vector-Hector Oct 31 '21 at 10:01
  • Its not working , and I am able to console log the values in globalstate , but when I pass it to child components it shows an empty array . – Spark Ignite Oct 31 '21 at 10:36
  • Ok, I see what went wrong. You're using `componentDidMount`, which is only called when the component is created. When the context updates, you can catch the event using the `render`, `componentDidUpdate` or `getSnapshotBeforeUpdate` – Vector-Hector Oct 31 '21 at 11:46
  • Hey it's working when I use componentdidupdate , but I'm not able setstate ....any idea how thats done . – Spark Ignite Oct 31 '21 at 12:29
  • Hey thanks a lot ,it working fine . – Spark Ignite Oct 31 '21 at 14:52
  • Hi, if you want to use setState, maybe a [Consumer](https://reactjs.org/docs/context.html#contextconsumer) could work for you. I haven't used it that way, but it might work out. – Vector-Hector Oct 31 '21 at 17:48

0 Answers0