javascriptreactjsstateunstated

Destructuring with unstated.js


I have this Unstated container:

import { Container } from 'unstated';
import axios from 'axios';

export default class CurrenciesContainer extends Container {
  state = { currencies: null };
  async fetch() {
    const { data: currencies } = await axios.get('http://localhost:8080/get-currencies');
    this.setState({ currencies });
  }
}

And this function that utilises it:

static renderCurrencies() {
  return (
    <Subscribe to={[CurrenciesContainer]}>
      {(currencies) => {
        if (!currencies.state.currencies) {
          currencies.fetch();
        }
        return <small>Currencies: {currencies.state.currencies}</small>;
      }}
    </Subscribe>
  );
}

I wanted to try and destructure the params coming into the <Subscribe> like so:

static renderCurrencies() {
  return (
    <Subscribe to={[CurrenciesContainer]}>
      {({ state, fetch }) => {
        if (!state.currencies) {
          fetch();
        }
        return <small>Currencies: {state.currencies}</small>;
      }}
    </Subscribe>
  );
}

But this breaks with Uncaught (in promise) TypeError: this.setState is not a function

Clearly it's not binding properly but I'm not sure why the destructuring of the function would change its binding. Anyone able to offer an explanation/way of doing it like this? Thanks!


Solution

  • Replace async fetch() {} with fetch = async () => {} to achieve the correct binding.

    Try this in your Unstated container:

    import { Container } from 'unstated';
    import axios from 'axios';
    
    export default class CurrenciesContainer extends Container {
      state = { currencies: null };
      fetch = async () => {
        const { data: currencies } = await axios.get('http://localhost:8080/get-currencies');
        this.setState({ currencies });
     }
    }