reactjsreact-contextunstated

Initializing the Container with API call unstated.js (React Context API)


I would like to simply initialize the Container state with data from an api call using unstated.js (a React Context wrapper).

I saw one example where the Container was instantiated with a couple vars:

import { Container} from 'unstated';

class WordlistContainer extends Container {

    constructor(...words) {
        super();

        this.state = {
            words: words
        };
    }
}


let wordList = new WordlistContainer('word1', 'word2');
export default wordList;

If I want to fetch some api data to pass into this Container's state - is this the right way to do it? Or should I pass props from a parent component? This is for loading data into a SPA when it first loads.


Solution

  • This ended up working:

    ​​import React, { Component } from 'react';
    ​​import RDOM from 'react-dom';
    ​​import { Container, Provider, Subscribe } from 'unstated';
    ​​
    ​​class ApiContainer extends Container {
    ​​  state = {
    ​​    loading: true,
    ​​    data: null
    ​​  }
    ​​  
    ​​  setApiResponseAsState = async () => {
    ​​    fetch.('someapi').then(res => res.jsoj()).then( data => this.setState({ data, loading: false });
    ​​  }
    ​​}
    ​​
    ​​class ApiConsumer extends Component {
    ​​  async componentDidMount() {
    ​​    this.props.setApiResponseAsState();
    ​​  }
    ​​  
    ​​  render() {
    ​​    return <div>{this.props.state}</div>
    ​​  }
    ​​}
    ​​
    ​​RDOM.render(
    ​​  <Provider>
    ​​    <Subscribe to={[ApiContainer]}>
    ​​      { props => <ApiConsumer {…props} />
    ​​      }
    ​​    </Subscribe>
    ​​  </Provider>
    ​​  , document.querySelector("#root");
    ​​)