Context empty after async initialisation

I am trying to fetch data from a backend API and initialise my FieldsContext. I am unable to do it, it returns an empty fields array in the Subfields component. I have spent hours on fixing it. But I eventually give up. Please take a look into this. Thanks in advance.
Here is my code

App.js

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css';
import Index from './components/pages/index/'

import FieldsProvider from './providers/fieldProvider'
import AuthProvider from './providers/authProvider'
import {BrowserRouter as Router,Switch,Route} from 'react-router-dom';
import SubFields from './components/pages/subfields';

function App() {

  
  return (
    
    <Router>
      <AuthProvider>
        <FieldsProvider>
          <Switch>
            <Route exact path="/" component={Index} />
            <Route exact path="/:fieldid/subfields" component={SubFields} />
          </Switch>
        </FieldsProvider>
      </AuthProvider>
    </Router>
    
  );
}

export default App;

FieldsContext.js

import React from 'react'



const FieldsContext = React.createContext();
export default FieldsContext

FieldsProvider.js

import React, { Component } from 'react'
import FieldsContext from '../libs/fieldContext'


export default class FieldsProvider extends Component {
    state = {fields:[]}
    

    getFields()
    {
            fetch('/api/fields')
            .then(res => res.json())
            .then(fields => this.setState({fields}));
    }
    async componentDidMount() {
        await this.getFields();
    }
    render() {
        return (
           <FieldsContext.Provider value={this.state} >
               {this.props.children}
           </FieldsContext.Provider>
        )
    }
}

Subfields.js

import React, { Component } from 'react'
import FieldsContext from '../../../libs/fieldContext'
import FieldsList from '../../Fields/fieldlist'
export default class SubFields extends Component {
    
     componentDidMount(){
        // const fieldId = this.props.match.params.fieldid;
        console.log(this.context);
        
    }
    render() {
        return (
            <div>
                
            </div>
        )
    }
}

SubFields.contextType = FieldsContext

163 thoughts on “Context empty after async initialisation”

  1. Losing an erection or being unable to become put up in many cases results from nerves, anxiety, or using liquor or other drugs. On occasion men problem hither exhibit, and sometimes they’re anxious almost whether or not having sexual intercourse is the ethical sentence, or whether they’re with the right partner.
    Source: tadalafil 5 mg

    Reply

Leave a Comment